//二分查找 默认查找有序数组
- (NSInteger)searchTarget:(NSInteger)target fromArr:(NSArray *)arr
{
if (arr.count < 1) {
return -1;
}
NSInteger start,mid,end;
start = 0;
mid = 0 ;
end = arr.count-1;
while (start < end-1) {//就剩两个数的时候 start = end - 1;这个条件跳出
mid = start + (end - start)/2;
if ([arr[mid] integerValue] > target) {
end = mid;
}else{
start = mid;
}
}
if (target == [arr[start] integerValue]) {
return start;
}
if (target == [arr[end] integerValue]) {
return end;
}
return -1;
}
//快速排序
- (void)sortArr:(NSMutableArray *)arr left:(NSInteger)left right:(NSInteger)right
{//@[@3,@4,@1,@6,@5,@2,@9,@7,@8]
if (left >= right) {//如果数组长度为0或1时返回 递归调用的必备跳出
return ;
}
NSInteger i,j,base;
i = left;
j = right;
base = [arr[left] integerValue];
while(i < j){//循环1️⃣
while([arr[j] integerValue] >= base&&i<j){
j--;
}
arr[i] = arr[j];
while ([arr[i] integerValue] <= base&&i<j) {
i++;
}
arr[j] = arr[i];
}
arr[i] = @(base);
[self sortArr:arr left:left right:i-1];
[self sortArr:arr left:i+1 right:right];
}
//快速排序
NSMutableArray *array = @[@3,@4,@1,@6,@5,@2,@9,@7,@8].mutableCopy;
[self sortArr:array left:0 right:array.count-1];
//二分查找
NSArray *arr = @[@1,@3,@4,@6,@7,@8,@9];
NSArray *arr0 = @[@2,@3,@5,@7,@8,@9];
NSArray *arr1 = @[@2,@3,@7,@7,@8,@9];
NSInteger i = [self searchTarget:7 fromArr:arr];
NSInteger j = [self searchTarget:7 fromArr:arr0];
NSInteger k = [self searchTarget:7 fromArr:arr1];
NSLog(@"---------%ld\n ===========%ld \n +++++++++++%ld",i,j,k);
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦