OC 中实现常用的算法

#在OC中实现常用的算法(冒泡,选择,快速,插入)

## 1.冒泡排序

- (void)viewDidLoad {

[super viewDidLoad];

//OC中常用的一些排序

NSArray *arr = @[@"1",@"2",@"5",@"3",@"6",@"9",@"5",];

NSMutableArray *oldArr = [NSMutableArray arrayWithArray:arr];

NSLog(@"%@",oldArr);

[self bubbleSort:oldArr];

[self selectionSort:oldArr];

[self insertSor:oldArr];

[self quickSort:oldArr leftIndex:1 rightIndex:5];

}

#pragma mark - bubbleSort

/**

①.冒泡排序算法

@param array参数

*/

- (void)bubbleSort:(NSMutableArray *)array {

for (int i = 0; i < array.count; i++) {

for (int j = 0; j < array.count-i-1; j++) {

if ([array[j+1]integerValue] < [array[j]integerValue]) {

int temp = [array[j] integerValue];

array[j] = array[j+1];

array[j+1] = [NSNumber numberWithInt:temp];

                    }

            }  

    }

NSLog(@"冒泡排序后: %@",array);

}

#pragma mark - selectionSort

/**

②.选择排序

@param array参数

*/

- (void)selectionSort:(NSMutableArray *)array {

for (int i = 0; i < array.count; i++) {

for (int j = i+1; j

if ([array[i]integerValue] > [array[j]integerValue]) {

int temp = [array[i] integerValue];

array[i] = array[j];

array[j] = [NSNumber numberWithInt:temp];

                }

          }

  }

NSLog(@"选择排序后: %@",array);

}

#pragma mark - insertSort

/**

③.插入排序

@param array参数

*/

- (void)insertSor:(NSMutableArray *)array {

for (int i = 1; i < array.count; i++) {

int temp = [array[i]integerValue];

for (int j = i-1; j>=0 && temp <[array[j] integerValue]; j--) {

array[j+1] = array[j];

array[j] = [NSNumber numberWithInt:temp];

             }

     }

NSLog(@"插入排序后: %@",array);

}

#pragma mark - quickSort

/**

④.快速排序

@param array参数

*/

- (void)quickSort:(NSMutableArray *)array leftIndex:(int)left rightIndex:(int)right {

if (left < right) {

int temp = [self getMiddleIndex:array leftIndex:left rightIndex:right];

[self quickSort:array leftIndex:left rightIndex:temp-1];

[self quickSort:array leftIndex:temp+1 rightIndex:right];

    }

NSLog(@"快速排序后: %@",array);

}

- (int)getMiddleIndex:(NSMutableArray *)array leftIndex:(int)left rightIndex:(int)right {

int tempValue = [array[left] integerValue];

while (left < right) {

while (left < right && tempValue <= [array[right] integerValue]) {

right--;

    }

if (left < right) {

array[left]=array[right];

   }

while (left < right && [array[left] integerValue] <= tempValue) {

left++;

   }

if (left < right) {

array[left] = array[right];

   }

   }

array[left] = [NSNumber numberWithInt:tempValue];

return left;

}

@end

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,793评论 0 33
  • //冒泡排序从大到小 (void)orderBubbleSort:(NSMutableArray *)mArray...
    onlyyourself阅读 266评论 0 0
  • 2017.06.17 今天要感恩爸爸妈妈,周五下班回来不知道为什么超级累。吃完晚饭趴在沙发上就睡着了,好像睡了有一...
    糊椒暇阅读 182评论 0 4
  • 呼朋唤友,灯红酒绿, 感情深,一口闷, 数杯下肚伤人胃。 路灯晃荡,脚步踉跄, 听力迟,口泛酸, 肚里杜康催人醉。...
    诗无名阅读 189评论 0 1
  • 大象文艺镇阅读 173评论 0 1