Bubble Sort
来源:互联网 发布:mac 搭建vps 编辑:程序博客网 时间:2024/04/28 14:32
冒泡算法, 一种简单的排序算法
复杂度: O(n^2)
伪代码:
bubbleSort( A : list of sortable items ) n = length(A) repeat swapped = false for i = 1 to n-1 inclusive do if A[i-1] > A[i] then swap(A[i-1], A[i]) swapped = true end if end for n = n - 1 until not swappedend procedureC语言实现:
// utility.h#ifndef _UTILITY_H_#define _UTILITY_H_#define ARR_SIZE(a) sizeof(a)/sizeof(a[0])print_arr(int arr[], int len){ int i=0; for (;i<len;i++) printf("%d, ", arr[i]); printf("\n");}#endif
#include <stdio.h>#include "utility.h"void BubbleSort(int arr[], int len){ int i=0, j=0, tmp=0; /*int arr_len = len;*/ for (i=0; i<len; i++) { for (j=1; j<len; j++) if (arr[j-1] > arr[j]) { tmp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = tmp; } /*print_arr(arr, arr_len);*/ len--; }}int main(){ int arr[] = {5,1,4,2,8,9,7,3,6,17,11}; int len = ARR_SIZE(arr); BubbleSort(arr, len); printf("bubble sort result:\n"); print_arr(arr, len); return 0;}
//运行结果:dennis@dennis-VirtualBox:~/project/sort$ ./bubblebubble sort result:1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 17,dennis@dennis-VirtualBox:~/project/sort$Python实现:
#!/usr/bin/env pythonimport randomdef bubble_sort(x, len): for i in range(len):swap=0 for j in range(len-1): if (x[j]>x[j+1]): (x[j], x[j+1]) = (x[j+1], x[j])swap=1if swap==0:print 'break at len:',lenbreak len = len -1if __name__ == '__main__': arr=[] len = 10 for i in range(len): arr.append(random.randint(1,100)) print 'list before sort:',arr bubble_sort(arr, len) print 'list after sort:',arr
##运行结果:dennis@dennis-VirtualBox:~/project/sort$ python bubble_sort.pylist before sort: [37, 13, 7, 75, 45, 40, 58, 96, 77, 74]break at len: 7list after sort: [7, 13, 37, 40, 45, 58, 74, 75, 77, 96]dennis@dennis-VirtualBox:~/project/sort$ python bubble_sort.pylist before sort: [71, 68, 88, 4, 80, 64, 50, 48, 69, 8]break at len: 2list after sort: [4, 8, 48, 50, 64, 68, 69, 71, 80, 88]dennis@dennis-VirtualBox:~/project/sort$
参考: Wikipedia Bubble sort
- Bubble sort
- Bubble Sort
- bubble sort
- Bubble Sort
- Bubble Sort
- bubble sort
- Bubble Sort
- Bubble Sort
- Bubble Sort
- Bubble Sort
- Bubble Sort
- Bubble Sort
- Bubble Sort
- Bubble sort
- Bubble Sort
- Bubble Sort
- Bubble Sort
- Bubble Sort
- SQL日期格式转换
- Study《JavaScript实现ArrayList》
- 重构全面总结
- VC++学习笔记(三)
- 约瑟夫环 & 猴王问题
- Bubble Sort
- 大素数“测试”
- 详解 Android 的 Activity 组件
- C++面向对象的书籍推荐
- This tag and its children can be replaced by one <TextView/> and a compound drawable
- web项目中各种路径的获取
- 关于 Installation error: INSTALL_FAILED_MISSING_SHARED_LIBRARY
- C++ 新建文件夹
- (Python编程)一个简单的C扩展模块