栈
二叉树
队列
堆
排序
冒泡排序
/*
* 冒泡排序:进行n次循环,一次循环,两两比较,必要时候交换位置
第一次循环:
700,0,11,800,9000,59,600,22,34,44
0,700,11,800,9000,59,600,22,34,44
0,11,700,800,9000,59,600,22,34,44
0,11,700,800,59,9000,600,22,34,44
0,11,700,800,59,600,9000,22,34,44
0,11,700,800,59,600,22,9000,34,44
0,11,700,800,59,600,22,34,9000,44
0,11,700,800,59,600,22,34,44,9000
第二次循环:
0,11,700,800,59,600,22,34,44
...
0,11,700,59,600,22,34,44,800
*/
- (void)bubbleSort:(NSMutableArray*)array{
int i = (int)[array count]-1;
int temp;
while (i > 0) {
for (int j = 0; j < i; j++) {
if ([array[j] intValue] > [array[j+1] intValue]) {
temp = [array[j + 1] intValue];
array[j + 1] = array[j];
array[j] = @(temp);
}
}
i--;
}
NSLog(@"排序后:%@",array);
}
归并排序
先分割一个再按照大小有序合并
基数排序
查找
二分查找(折半查找)
关键点:必须是先排好序的数组,计算的到middleIndex,然后再让target和数组中middleIndex处的值进行对比
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *array = @[@"0",@"11",@"22",@"34",@"44",@"59",@"600",@"700",@"800",@"9000"];
[self binarySearchByRecursive:array target:1000000 startIndex:0 endIndex:9];
}
/*
* 二分查找-递归
*/
- (void)binarySearchByRecursive:(NSArray*)array target:(int)target startIndex:(int)startIndex endIndex:(int)endIndex{
int middleIndex = (startIndex + endIndex) / 2;
NSLog(@"startIndex:[%d]=%@ endIndex:[%d]=%@ middleIndex:[%d]=%@",startIndex,array[startIndex],endIndex,array[endIndex],middleIndex,array[middleIndex]);
if (target > [array[middleIndex] intValue]) {
if (startIndex == endIndex) {
NSLog(@"没找到");
return;
}
NSLog(@"find+...");
[self binarySearchByRecursive:array target:target startIndex:middleIndex+1 endIndex:endIndex];
}else if(target < [array[middleIndex] intValue]){
if (startIndex == middleIndex) {
NSLog(@"没找到");
return;
}
NSLog(@"find-...");
[self binarySearchByRecursive:array target:target startIndex:startIndex endIndex:middleIndex-1];
}else if([array[middleIndex] intValue] == target){
NSLog(@"找到了,值是:%d",[array[middleIndex] intValue]);
}
}
@end