[Swift Algorithm] Bubble sort

作者: sunlitamo | 来源:发表于2016-07-16 11:19 被阅读63次

    Swift

    func bubbleSort(src: inout [Int]) {
        
        let count = src.count
    
        for i in 0 ..< count {
            
            for j in 1 ..< count - i {
                
                if src[j - 1] < src[j] { swap(&src[j - 1], &src[j]) }
            }
        }
    }
    

    Objective-C

    NSMutableArray* bubbleSort(NSMutableArray *arr)
    {
        BOOL swapped = YES;
        int k = 0;
        
        while (swapped) {
            swapped = NO;
            
            for (int i = 0; i < arr.count - 1 - k; i++) {
                if ([arr objectAtIndex:i] > [[arr objectAtIndex:i + 1]) {
                    [arr exchangeObjectAtIndex:i withObjectAtIndex:i + 1];
                    swapped = YES;
                }
            }
            k++;
        }
        return arr;
    }
    

    相关文章

      网友评论

        本文标题:[Swift Algorithm] Bubble sort

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