美文网首页
01-冒泡排序(python、oc)

01-冒泡排序(python、oc)

作者: Young_Blood | 来源:发表于2017-09-11 10:06 被阅读14次

简述:从前往后,如果我比你大,那么我就和你交换位置

  • 最优时间复杂度 O(n)
  • 最坏时间复杂度 O(n²)
  • 稳定性:稳定
python3
def bubble_sort(alist):
    n = len(alist)
    for i in range(n - 1):
        for j in range(n - 1 - i):
            if alist[j] > alist[j + 1]:
                alist[j],alist[j + 1] = alist[j + 1], alist[j]

if __name__ == "__main__":
    li = [54,23,12,44,55,88,1]
    print(li)
    bubble_sort(li)
    print(li)

objective-c

- (void)bubble_sort:(NSMutableArray *)arr{
    NSLog(@"%s", __func__);
    int count = 0;
    for (int i = 0; i < arr.count - 1; i++) {
        for (int j = 0; j < arr.count - 1 - i; j++) {
            if (arr[j] > arr[j+1]) {
                NSNumber *temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
                count++;
            }
        }
        if (count == 0) {
            return;
        }
    }
}

相关文章

网友评论

      本文标题:01-冒泡排序(python、oc)

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