基本算法

  • 1.冒泡算法
   NSMutableArray * allData = [NSMutableArray array];
    for (int i = 0; i < 10; i++) {
        [allData addObject:@(i)];
    }
    for (int i = 0; i < allData.count-1; i++) {
        for (int j = 0; j < allData.count-1-i; j++) {
            NSInteger a = [allData[j] integerValue];
            NSInteger b = [allData[j+1] integerValue];
            if (a < b) {
                allData[j] = @(b);
                allData[j+1] = @(a);
            }
        }
    }

  • 2.选择算法
  NSMutableArray * allData2 = [NSMutableArray array];
    for (int i = 0; i < 10; i++) {
        [allData2 addObject:@(i)];
    }
    for (int i = 0; i< allData2.count -1; i++) {

        for (int j = i +1; j < allData2.count; j++) {
            NSInteger a = [allData2[i] integerValue];
            NSInteger b = [allData2[j] integerValue];
            if (a < b) {
                allData2[i] = @(b);
                allData2[j] = @(a);
            }
        }
    }

*上面这两个算法耗时基本相同.

  • 插入算法
  NSMutableArray * allData3 = [NSMutableArray array];
    for (int i = 0; i < 1000; i++) {
        [allData3 addObject:@(i)];
    }
    for (int i = 0; i < allData3.count; i++) {
        for (int j = i; j >0&&(allData3[j]

*耗时比上面两个小

  • 快速排序 StartIndex:0 EndIndex : arr.count-1
-(void)QuickSort:(NSMutableArray *)list StartIndex:(NSInteger)startIndex EndIndex:(NSInteger)endIndex
{
    
    if (startIndex >= endIndex) {
        return;
    }
    NSNumber * temp = [list objectAtIndex:startIndex];
    NSInteger tempIndex = startIndex; //临时索引 处理交换位置(即下一个交换的对象的位置)
    
    for(int i = (int)startIndex + 1 ; i <= endIndex ; i++){
        
        NSNumber *t = [list objectAtIndex:i];
        
        if([temp intValue] > [t intValue]){
            
            tempIndex = tempIndex + 1;

            [list exchangeObjectAtIndex:tempIndex withObjectAtIndex:i];
            
        }
        
    }

    [list exchangeObjectAtIndex:tempIndex withObjectAtIndex:startIndex];
    [self QuickSort:list StartIndex:startIndex EndIndex:tempIndex-1];
    [self QuickSort:list StartIndex:tempIndex+1 EndIndex:endIndex];
    
}

你可能感兴趣的:(基本算法)