/*
- 冒泡排序,相邻两个对比,前者比后者大,交换位置
*/
pragma mark - 冒泡降序排序
- (void)bubbleDescendingOrderSortWithArray:(NSMutableArray *)descendingArr
{
for (int i = 0; i < descendingArr.count; i++) {
for (int j = 0; j < descendingArr.count - 1 - i; j++) {
if ([descendingArr[j] intValue] < [descendingArr[j + 1] intValue]) {
int tmp = [descendingArr[j] intValue];
descendingArr[j] = descendingArr[j + 1];
descendingArr[j + 1] = [NSNumber numberWithInt:tmp];
}
}
}
NSLog(@"冒泡降序排序后结果:%@", descendingArr);
}
、、、、、、、、、、、
/*
- 选择排序,标记最小值,循环比较,替换最小值
*/
pragma mark - 选择升序排序
- (void)selectionAscendingOrderSortWithArray:(NSMutableArray *)ascendingArr
{
for (int i = 0; i < ascendingArr.count; i ++) {
for (int j = i + 1; j < ascendingArr.count; j ++) {
if ([ascendingArr[i] integerValue] > [ascendingArr[j] integerValue]) {
int temp = [ascendingArr[i] intValue];
ascendingArr[i] = ascendingArr[j];
ascendingArr[j] = [NSNumber numberWithInt:temp];
}
}
}
NSLog(@"选择升序排序后结果:%@", ascendingArr);
}
、、、、、、、、、、、、、、、、
/*
- 插入排序,逐个元素拿出来,与其左边元素逐个对比,碰到比该元素小的元素,则插入在对比元素后
*/
pragma mark - 插入升序排序
- (void)insertionAscendingOrderSort:(NSMutableArray *)ascendingArr
{
for (NSInteger i = 1; i < ascendingArr.count; i ++) {
NSInteger temp = [ascendingArr[i] integerValue];
for (NSInteger j = i - 1; j >= 0 && temp < [ascendingArr[j] integerValue]; j --) {
ascendingArr[j + 1] = ascendingArr[j];
ascendingArr[j] = [NSNumber numberWithInteger:temp];
}
}
NSLog(@"插入升序排序结果:%@",ascendingArr);
}
、、、、、、、、、、、、、、、、
<pre>#pragma mark - 快速升序排序
- (void)quickAscendingOrderSort:(NSMutableArray *)arr leftIndex:(NSInteger)left rightIndex:(NSInteger)right
{ if (left < right) {
NSInteger temp = [self getMiddleIndex:arr leftIndex:left rightIndex:right];
[self quickAscendingOrderSort:arr leftIndex:left rightIndex:temp - 1];
[self quickAscendingOrderSort:arr leftIndex:temp + 1 rightIndex:right];
}
NSLog(@"快速升序排序结果:%@", arr);
} - (NSInteger)getMiddleIndex:(NSMutableArray *)arr leftIndex:(NSInteger)left rightIndex:(NSInteger)right
{
NSInteger tempValue = [arr[left] integerValue]; while (left < right) { while (left < right && tempValue <= [arr[right] integerValue]) {
right --;
} if (left < right) {
arr[left] = arr[right];
} while (left < right && [arr[left] integerValue] <= tempValue) {
left ++;
} if (left < right) {
arr[right] = arr[left];
}
}
arr[left] = [NSNumber numberWithInteger:tempValue]; return left;
}