当前位置:  首页>> 技术小册>> 数据结构与算法(中)

核心:冒泡,持续比较相邻元素,大的挪到后面,因此大的会逐步往后挪,故称之为冒泡。
实现
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[] array) {
  11. int len = array.length;
  12. for (int i = 0; i < len; i++) {
  13. for (int item : array) {
  14. System.out.print(item + " ");
  15. }
  16. System.out.println();
  17. for (int j = 1; j < len - i; j++) {
  18. if (array[j - 1] > array[j]) {
  19. int temp = array[j - 1];
  20. array[j - 1] = array[j];
  21. array[j] = temp;
  22. }
  23. }
  24. }
  25. }
  26. }

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


该分类下的相关小册推荐: