冒泡排序:
NSMutableArray *p = [[NSMutableArray alloc] initWithObjects:@"3",@"5",@"4",@"1",nil]; for (int i = 0; i<[p count]; i++) { for (int j=i+1; j<[p count]; j++) { int a = [[p objectAtIndex:i] intValue]; // NSLog(@"a = %d",a); int b = [[p objectAtIndex:j] intValue]; // NSLog(@"b = %d",b); // NSLog(@"------"); if (a > b) { [p replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%d",b]]; [p replaceObjectAtIndex:j withObject:[NSString stringWithFormat:@"%d",a]]; } } } NSLog(@"%@",p);
NSArray * testArray = @[@12,@188,@26,@24,@17,@88]; NSMutableArray * nA = [NSMutableArray arrayWithArray: testArray]; for (NSInteger i = 0; i < nA.count; i++) { //外层循环次数 for (NSInteger j = 0; j < nA.count - 1 - i; j++) { //内层循环次数,(外层没循环1次则会在数组最后1个位置获取到1个最大值,所有此处循环次数为 (总次数 - 1 - i) 次) NSInteger temp = [nA[j + 1] integerValue]; NSLog(@"%d",temp); if ([nA[j] integerValue] > [nA[j + 1] integerValue]) { //如果前面一个大于后面一个,则交换位置 nA[j + 1] = nA[j]; nA[j] = [NSNumber numberWithInt: temp]; } NSLog(@"%@",nA); } } NSLog(@"%@",nA);