Bubble Sort - 冒泡排序

核心:冒泡,持续比较相邻元素,大的挪到后面,因此大的会逐步往后挪,故称之为冒泡。

Bubble Sort

Implementation

Python

  1. #!/usr/bin/env python
  2. def bubbleSort(alist):
  3. for i in xrange(len(alist)):
  4. print(alist)
  5. for j in xrange(1, len(alist) - i):
  6. if alist[j - 1] > alist[j]:
  7. alist[j - 1], alist[j] = alist[j], alist[j - 1]
  8. return alist
  9. unsorted_list = [6, 5, 3, 1, 8, 7, 2, 4]
  10. print(bubbleSort(unsorted_list))

Java

  1. public class Sort {
  2. public static void main(String[] args) {
  3. int[] unsortedArray = new int[]{6, 5, 3, 1, 8, 7, 2, 4};
  4. bubbleSort(unsortedArray);
  5. System.out.println("After sort: ");
  6. for (int item : unsortedArray) {
  7. System.out.print(item + " ");
  8. }
  9. }
  10. public static void bubbleSort(int[] nums) {
  11. int len = nums.length;
  12. for (int i = 0; i < len; i++) {
  13. for (int num : nums) {
  14. System.out.print(num + " ");
  15. }
  16. System.out.println();
  17. for (int j = 1; j < len - i; j++) {
  18. if (nums[j - 1] > nums[j]) {
  19. int temp = nums[j - 1];
  20. nums[j - 1] = nums[j];
  21. nums[j] = temp;
  22. }
  23. }
  24. }
  25. }
  26. }

复杂度分析

平均情况与最坏情况均为 O(n^2), 使用了 temp 作为临时交换变量,空间复杂度为 O(1).

Reference