不喜勿喷, 不吝指教
冒泡排序
//冒泡降序排序
- (void)bubbleDescendingSort:(NSMutableArray *)arr {
for (int i = 0; i < arr.count; i ++) {
for (int j = 0; j < arr.count - 1 - i; j ++) {
if (arr[j] < arr[j+1]) {
int num = [arr[j] intValue];
arr[j] = arr[j+1];
arr[j+1] = [NSNumber numberWithInt:num];
}
}
}
NSLog(@"冒泡降序排序后结果:%@", arr);
}
//冒泡升序排序
- (void)bubbleAscendingSort:(NSMutableArray *)arr {
for (int i = 0; i < arr.count; i ++) {
for (int j = 0; j < arr.count - 1 -i; j ++) {
if (arr[j] > arr[j + 1]) {
[arr exchangeObjectAtIndex:j+1 withObjectAtIndex:j];
}
}
}
NSLog(@"冒泡升序排序后结果:%@", arr);
}
选择排序
//选择降序排序
- (void)selectionDescendingSort:(NSMutableArray *)arr {
for (int i = 0 ; i < arr.count; i ++) {
for (int j = i+1; j < arr.count; j ++) {
if (arr[i] < arr[j]) {
int num = [arr[i] intValue];
arr[i] = arr[j];
arr[j] = [NSNumber numberWithInt:num];
}
}
}
NSLog(@"选择降序排序后结果:%@", arr);
}
//选择升序排序
- (void)selectionAscendingSort:(NSMutableArray *)arr {
for (int i = 0; i < arr.count; i ++) {
for (int j = i +1; j < arr.count; j ++) {
if (arr[i] > arr[j]) {
[arr exchangeObjectAtIndex:i withObjectAtIndex:j];
}
}
}
NSLog(@"选择升序排序后结果:%@", arr);
}
插入排序
//插入升序排序
- (void)insertAscendingSort:(NSMutableArray *)arr {
for (int i = 1; i < arr.count ; i ++) {
int num = [arr[i] intValue];
for (int j = i - 1; j >= 0 && num < [arr[j] intValue]; j -- ) {
arr[j+1] = arr[j];
arr[j] = [NSNumber numberWithInt:num];
NSString * str = [arr componentsJoinedByString:@","];
NSLog(@"------------->结果:%@",str);
}
}
NSLog(@"插入升序排序结果:%@",arr);
}
//插入降序排序
- (void)insertDescendingSort:(NSMutableArray *)arr {
for (int i = 1; i < arr.count; i++) {
int j = i; // 确定当前坑的位置
int temp = [arr[j] intValue]; // 目标出列
while (j > 0 && temp < [arr[j - 1] intValue]) {
arr[j] = arr[j - 1]; // 向后顶大的
j --; // 向前移坑
}
arr[j] = [NSNumber numberWithInt:temp]; // 目标进坑
}
NSLog(@"插入降序排序结果:%@",[[arr reverseObjectEnumerator] allObjects]);
}
快速排序
//快速升序排序
- (void)quickDescendingSort:(NSMutableArray *)arr leftIndex:(NSInteger)left rightIndex:(NSInteger)right {
if (left < right) {
NSInteger temNum = [self getMiddleIndex:arr leftIndex:left rightIndex:right];
[self quickDescendingSort:arr leftIndex:left rightIndex:temNum - 1];
[self quickDescendingSort:arr leftIndex:temNum + 1 rightIndex:right];
}
NSLog(@"快速升序排序结果:%@", arr);
}
- (NSInteger)getMiddleIndex:(NSMutableArray *)middleArr leftIndex:(NSInteger)left rightIndex:(NSInteger)right {
NSInteger num = [middleArr[left] integerValue];
while (left < right) {
while (left < right && num <= [middleArr[right] integerValue] ) {
right --;
}
if (left < right) {
middleArr[left] = middleArr[right];
}
while (left < right && [middleArr[left] integerValue] <= num) {
left ++;
}
if (left < right) {
middleArr[right] = middleArr[left];
}
}
middleArr[left] = [NSNumber numberWithInteger:num];
return left;
}
网友评论