伪代码:
int put list[1->n]; for i <- n to 1 for j = 0 to i-1 if list[j]>list[j+1] swap(list[j],list[j+1])
C++实现:
#include<iostream> //交换数据 inline void my_swap(int &a, int &b) { int temp = a; a = b; b =temp; } //冒泡排序 void bubble_sort(int *arr,int n) { for (int i = n-1; i >= 0; --i) for (int j = 0; j <= i-1; ++j) { if (arr[j] > arr[j+1]) my_swap(arr[j],arr[j+1]); } } //打印数组 void dis_arr(int *a, int n) { std::cout << "The array is: "; for (int i = 0; i< n;++i) { std::cout << a[i] << " "; } std::cout << std::endl; } int main() { int arr[] = {1,-1,90,20,8,-80}; int n = sizeof(arr)/sizeof(*arr); dis_arr(arr,n); bubble_sort(arr,n); dis_arr(arr,n); }
根据同学说的,上面说的冒泡排序要进行n*n-1次,有可能排序已经完成,但仍在进行循环,因此可以设置标志位,如果已经完成排序,就退出:
改进算法为:
#include<iostream> //交换数据 inline void my_swap(int &a, int &b) { int temp = a; a = b; b =temp; } //打印数组 void dis_arr(int *a, int n) { std::cout << "The array is: "; for (int i = 0; i< n;++i) { std::cout << a[i] << " "; } std::cout << std::endl; } //冒泡排序 void bubble_sort(int *arr,int n) { bool flag = 1; for (int i = n-1; i >= 0; --i) { //每次前i-1个数的最大值冒泡到最后 flag = 1; for (int j = 0; j <= i-1; ++j) { if (arr[j] > arr[j+1]) { my_swap(arr[j],arr[j+1]); flag = 0; } } if(flag) return; std::cout << "第"<< n-i << "次排序:"; dis_arr(arr, n); } } int main() { int arr[] = {36,18,52,39,27,32,12,91,8}; int n = sizeof(arr)/sizeof(*arr); dis_arr(arr,n); bubble_sort(arr,n); dis_arr(arr,n); }