美文网首页
OC排序算法整理

OC排序算法整理

作者: 没打伞的鱼 | 来源:发表于2019-10-18 16:25 被阅读0次
    #pragma mark - 插入排序
    -(void)insertionSort{
        
         NSMutableArray * notSortedArray = [NSMutableArray arrayWithObjects: @"1",@"8",@"2",@"14",@"7",@"13",@"5",@"9",@"98",nil];
        
        
        for (NSInteger i = 0 ; i < notSortedArray.count -1; i++){
            
            for (NSInteger j = i+1; j >0; j --) {
                
                if([notSortedArray[j] intValue] < [notSortedArray[j-1] intValue]){
                    [notSortedArray exchangeObjectAtIndex:j-1 withObjectAtIndex:j];
                    
                }else{
                    break;
                }
            }
            
         }
        
        NSLog(@"%@",notSortedArray);
    }
    
    
    
    
    #pragma mark - 选择排序
    /**
     从第一个位置开始比较,找出最小的,和第一个位置互换,开始下一轮。
     类似于打擂台,都去与第一位置的人对比,选出最小的;然后再都去与第二位置的对比
     */
    
    -(void)selectionSort{
        
        
        NSMutableArray * notSortedArray = [NSMutableArray arrayWithObjects: @"1",@"8",@"2",@"14",@"7",@"13",@"5",@"9",@"98",nil];
        
        for (NSInteger i = 0 ; i < notSortedArray.count - 1; i++){
            
            for (NSInteger j = i+1; j < notSortedArray.count ; j ++) {
                if([notSortedArray[j] intValue] < [notSortedArray[i] intValue]){
                    [notSortedArray exchangeObjectAtIndex:j withObjectAtIndex:i];
                }
            }
        }
        
         NSLog(@"%@",notSortedArray);
        
    }
    
    
    
    

    冒泡排序

    原理


    IMG_0056.jpg
    /**
     冒泡排序,相邻两个对比,前者比后者大,交换位置
     */
    -(void)bubbleSort{
        
    
        NSMutableArray * notSortedArray = [NSMutableArray arrayWithObjects: @"1",@"8",@"2",@"14",@"7",@"13",@"5",@"9",nil];
        for (NSInteger i = 0 ; i < notSortedArray.count - 1; i++){
            //第一次外循环找出最大的数,第二次外循环找出第二大的数……总共需要n-1次外循环
    
            for (NSInteger j = 0; j < notSortedArray.count -1-i;j++) {
                if([notSortedArray[j] intValue] > [notSortedArray[j+1] intValue]){
                    [notSortedArray exchangeObjectAtIndex:j+1 withObjectAtIndex:j];
                }
    
            }
        }
    
        NSLog(@"%@",notSortedArray);
    
    }
    

    相关文章

      网友评论

          本文标题:OC排序算法整理

          本文链接:https://www.haomeiwen.com/subject/jkxwmctx.html