排序算法

给一个无序数组排序

NSMutableArray *numList = [NSMutableArray arrayWithArray:@[@"3",@"22",@"1",@"8",@"55",@"2",@"33",@"9",@"12"]];

冒泡排序

for (int index = 0; index < numList.count-1; index++) {
	BOOL bSort = NO;
	for (int jndex = 0; jndex < numList.count-1-index; jndex++) {
		int iLeft = [numList[jndex] intValue];
        int iRight = [numList[jndex+1] intValue];
        if (iLeft > iRight) {
        	[numList exchangeObjectAtIndex:jndex withObjectAtIndex:jndex+1];
            bSort = YES;
        }
   	}
    if (!bSort) {
      	break;
 	}
}

选择排序

for (int index = 0; index < numList.count; index++) {
  	int minIndex = index;
  	for (int jndex = index+1; jndex < numList.count; jndex++) {
      	int minValue = [numList[minIndex] intValue];
       	int jvalue = [numList[jndex] intValue];
     	if (jvalue < minValue) {
         	minIndex = jndex;
    	}
 	}
 	[numList exchangeObjectAtIndex:index withObjectAtIndex:minIndex];
}

快速排序

+ (void)quickSort:(NSMutableArray *)list low:(int)iLow hith:(int)iHigh {
    if (iLow >= iHigh) {
        return;
    }

    int index = iLow;
    int jndex = iHigh;
    id key = list[index];
    while (index < jndex) {
        while (index < jndex && [list[jndex] intValue] >= [key intValue]) {
            jndex--;
        }
        if (index == jndex) {
            break;
        }
        list[index++] = list[jndex];

        while (index < jndex && [list[index] intValue] <= [key intValue]) {
            index++;
        }
        list[jndex--] = list[index];
    }
    list[index] = key;
    [self quickSort:list low:iLow hith:index-1];
    [self quickSort:list low:index+1 hith:iHigh];
}

插入排序

for (int index = 0; index < numList.count-1; index++) {
   	int iLeft = [numList[index] intValue];
   	int iRight = [numList[index+1] intValue];
   	if (iRight < iLeft) {
      	int iTemp = iRight;
       	for (int jndex = index+1; jndex > 0 && [numList[jndex-1] intValue] > iTemp; jndex--) {
          	[numList exchangeObjectAtIndex:jndex-1 withObjectAtIndex:jndex];
     	}
 	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值