冒泡排序:
- (void)maoPaoSort:(NSArray *)arr{
NSMutableArray *getArr = [[NSMutableArray alloc]initWithArray:arr];
int abc = 0;
NSInteger count = getArr.count;
for (NSInteger i = 0; i < count - 1; i++) {
for (NSInteger j = 0; j < count - 1 - i; j++) {
abc++;
NSInteger a = [getArr [j] integerValue];
NSInteger b = [getArr [j+1] integerValue];
if (a < b) {
NSNumber *temp = getArr[j];
getArr[j] = getArr[j+1];
getArr[j+1] = temp;
}
}
}
NSLog(@"排序后的数组===%@",getArr);
NSLog(@"循环次数%d",abc);
}
选择排序
- (void)selectSort:(NSArray *)arr{
//每次轮询找出最小的那一个然后放到数组前面
NSMutableArray *getArr = [[NSMutableArray alloc]initWithArray:arr];
NSInteger count = getArr.count;
int abc = 0;
for (NSInteger i = 0; i < count - 1; i++) {
NSInteger minValue = [getArr[i] integerValue];
NSInteger minIndex = i;
for (NSInteger j = i+1; j < count; j++) {
NSInteger temp = [getArr[j] integerValue];
if (minValue < temp ) {
minValue = temp;
minIndex = j;
}
abc++;
}
[getArr exchangeObjectAtIndex:minIndex withObjectAtIndex:i];
}
NSLog(@"排序后的数组===%@",getArr);
NSLog(@"循环次数%d",abc);
}
直接插入排序
- (void)directInsertSort:(NSArray *)arr{
NSMutableArray *getArr = [[NSMutableArray alloc]initWithArray:arr];
NSInteger count = getArr.count;
int abc = 0;
for (NSInteger i = 1 ; i < count; i++) {
NSInteger tempIndex = i;
NSInteger tempValue = [getArr[i] integerValue];
NSLog(@"__%ld",(long)tempValue);
while (tempIndex > 0 && tempValue < [getArr[tempIndex-1] integerValue]) {
getArr[tempIndex] = getArr[tempIndex - 1];
tempIndex--;
abc++;
}
getArr[tempIndex] = @(tempValue) ;
}
NSLog(@"插入排序后的数组===%@",getArr);
NSLog(@"循环次数%d",abc);
}
快速排序
- (void)fastSort:(NSMutableArray *)getArr leftIndex:(NSInteger)left rightIndex:(NSInteger)right{
if (left > right) {
return;
}
// NSInteger count = getArr.count;
NSInteger i = left;
NSInteger j = right;
NSInteger key = [getArr[i]integerValue];
while (i < j) {
while (i < j && key >= [getArr[j]integerValue]) {
j--;
}
getArr[i] = getArr[j];
while (i < j && key <= [getArr[i]integerValue]) {
i++;
}
getArr[j] = getArr[i];
}
getArr[i] = @(key);
[self fastSort:getArr leftIndex:left rightIndex:i-1];
[self fastSort:getArr leftIndex:i+1 rightIndex:right];
// NSLog(@"排序后的数组===%@",getArr);
}
网友评论