//选择排序O(n²)
- (void)selectSort{
NSMutableArray *arr =[ [NSMutableArray alloc] initWithObjects:@"2",@"9",@"19",@"1",@"80",nil];
NSInteger length = arr.count;
for (NSInteger i = 0; i < length - 1; i++) { //趟数
for (NSInteger j = i + 1; j < length; j++) { //比较次数
if ([arr[i] integerValue] > [arr[j] integerValue]) {
NSInteger temp = [arr[i] integerValue];
arr[i] = arr[j];
arr[j] = [NSString stringWithFormat:@"%ld",(long)temp];
}
}
}
}
//冒泡排序O(n²)
- (void)bublleSort{
NSMutableArray *arr =[ [NSMutableArray alloc] initWithObjects:@"5",@"19",@"2",@"21",@"18",nil];
NSInteger length = arr.count;
for (NSInteger i = 0; i < length - 1; i++) { //趟数
for (NSInteger j = 0; j < length -i- 1; j++) { //比较次数
if ([arr[j] integerValue] > [arr[j+1] integerValue]) {
NSInteger temp = [arr[j] integerValue];
arr[j] = arr[j+1];
arr[j+1] = [NSString stringWithFormat:@"%ld",(long)temp];
}
}
}
}
//快速排序O(nlogn)
- (void)sortwithleft:(NSInteger)left right:(NSInteger)right{
if(left >= right)/*如果左边索引大于或者等于右边的索引就代表已经整理完成一个组了*/
{
return;
}
NSInteger i = left;
NSInteger j = right;
NSInteger key = [self.list[left] integerValue];
if (left < right){
while(i<j){ // 此处的while循环结束,则完成了元素key的位置调整
while(i<j && key<=[self.list[j] integerValue]){
j--;
}
self.list[i] = self.list[j];
while(i<j && key>=[self.list[i] integerValue]){
i++;
}
self.list[j] = self.list[i];
self.list[i] = [NSString stringWithFormat:@"%ld",(long)key]; //此处不可遗漏
}
[self sortwithleft:left right:i-1];
[self sortwithleft:i+1 right:right];
}
}
//二分查找,默认为有序数组O(log2n)
- (NSInteger)compare:(NSArray *)array target:(NSInteger)target{
if (!array.count) {
return -1;//数组无元素,返回-1;
}
NSInteger low = 0;//数组起始元素下标
NSInteger high = array.count - 1;//数组最后元素的下标
while (low <= high) {
NSInteger mid = low + ((high - low)/2);
//第mid项的内容
NSInteger num = [[array objectAtIndex:mid] integerValue];
if (target == num) {
return mid;
}
else if (num > target){
high = mid - 1;//左边进行查找
}else{
low = mid + 1;//右边进行查找
}
}
return -1;//数组中不存该数,返回-1;
}