OC算法

(更新)引用简书的一篇文章:https://www.jianshu.com/p/4f8e4071f85b

冒泡排序:
image

1
2
3
4
5
6
7
8
9
10
11
12
13
NSMutableArray * array = [[NSMutableArray alloc]initWithObjects:@"15",@"4",@"7",@"9",@"1",@"3", nil];

for (int i = 0; i < array.count -1; i++) {
for (int j = 0; j < array.count-1-i; j++) {

if ([array[j] integerValue] > [array[j+1] integerValue]) {
array[j] = @([array[j] integerValue] + [array[j+1] integerValue]);
array[j+1] = @([array[j] integerValue] - [array[j+1] integerValue]);
array[j] = @([array[j] integerValue] - [array[j+1] integerValue]);
}
}
}
NSLog(@"%@",array);

.

插入排序:
image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
NSMutableArray * array = [[NSMutableArray alloc]initWithObjects:@"4",@"15",@"7",@"9",@"1",@"3", nil];

for (int i = 1; i < array.count; i++) {

int j = i;
int mark = [array[i] intValue];

while (j > 0 && [array[j-1] intValue] > mark) {
array[j] = array[j-1];
j--;
}
array[j] = @(mark);
}
NSLog(@"arr = %@",array);

.

快速排序:
image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
NSMutableArray * array = [[NSMutableArray alloc]initWithObjects:@(15),@(4),@(7),@(9),@(1),@(3), nil];
//调用方法
[self sortedArray:array left:0 right:array1.count-1];
NSLog(@"%@",array);

- (void)sortedArray:(NSMutableArray *)array left:(NSInteger)left right:(NSInteger)right
{
if (left >= right) {
return;
}

NSInteger i = left;
NSInteger j = right;
NSInteger key = [array[i] integerValue];

while (i < j) {
while (i<j && [array[j] integerValue] >= key) {
j--;
}
array[i] = array[j];

while (i<j && [array[i] integerValue] <= key) {
i++;
}
array[j] = array[i];
}
array[i] = @(key);

[self sortedArray:array left:0 right:i-1];
[self sortedArray:array left:i+1 right:right];
}