快速排序
//
// ViewController.m
// quicksort
//
// Created by zhangyifan on 2021/9/28.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSMutableArray *arr = [NSMutableArray arrayWithObjects:@15,@14,@22,@56,@19,@2,@9,@6,@3,@8,@5,@7,@23,@15,@34, nil];
[self quicksort:arr start:0 end:arr.count-1];
NSLog(@"我拍好了 %@ ",arr);
}
- (void)quicksort:(NSMutableArray *)marr start:(NSInteger)s end:(NSInteger)e{
if (s >= e){
return;
}
int k = [marr[s] intValue];
NSInteger i = s,j = e;
while (i < j) {
while ((i < j) && ([marr[j] intValue] >= k)) {
j--;
}
[self swap:marr indexa:i indexb:j];
while ( (i < j) && ([marr[i] intValue] < k)) {
i++;
}
[self swap:marr indexa:i indexb:j];
}
[self quicksort:marr start:s end:j];
[self quicksort:marr start:j+1 end:e];
}
- (void)swap:(NSMutableArray *)m indexa:(NSInteger)a indexb:(NSInteger)b{
NSNumber *n = m[a];
m[a] = m[b];
m[b] = n;
}
@end