二维数组查找数字的OC实现
-(void)findNumWithNum:(NSArray<NSArray *>)num rows:(int)rows columns:(int)columns number:(int)number
{
BOOL reuslt = false;
int row = 0;
int column = columns-1;
if (rows&&columns) {
//右上角
while (row<rows&&columns>=0) {
if (num[row][column]==number) {
reuslt = true;
break;
}else if(num[row][column]>number){
//del col
column--;
}else{
row++;
}
}
}
}
OC 二分查找的实现
- (void)viewDidLoad {
[super viewDidLoad];
NSArray * array1 = @[@1,@2,@3,@4,@5,@6,@7,@9];
int result = [self compare:array1 target:@9];
//在这里打印结果看是否有相等的值
NSLog(@"%d",result);
}
- (int)compare:(NSArray *)array target:(int)target{
if (!array.count) {
return -1;
}
unsigned int low = 0;
unsigned int high = array.count - 1;
while (low <= high) {
//会有一些朋友看到有些人是( low + high ) / 2这样写的,但是这样写有一点不好,就是low+high会出现整数溢出的情况,如果存在溢出,你再除以2也是没有用的,所以不能这么写
int mid = low + ((high - low)/2);
//第mid项的内容
int num = [array objectAtIndex:mid];
if (target == num) {
return low;
}else if (num > target){
high = mid - 1;//左边进行查找
}else{
low = mid +1;//右边进行查找
}
}
return -1;//返回-1是没找到
}
快速排序
-(void)quickSort:(CFArrayRef*)arr L:(int)L R:(int)R{
int i = L;
int j = R;
int mid = arr[(L+R)/2];
while (i<=j) {
while (mid>arr[i]) {
i++;
}
while (mid<=arr[j]) {
j--;
}
if (i<=j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
if (L<j) {
[self quickSort:arr L:L R:j];
}
if (i<R) {
[self quickSort:arr L:i R:R];
}
}
网友评论