Key points: Scan the data from left to right, select the largest data, and put it on the right
Code:
#include <iostream>
using namespace std;
void bubble_sort(int list[], int n)
{
for (int i = 0; i < n - 1; i++) //比较n-1次
{
for (int j = 0; j < n - 1 - i; j++) //每一次循环少比较一次
{
if(list[j]> list[j + 1])
swap(list[j], list[j + 1]);
}
}
}
int main()
{
int arry[10] = {2,1,4,5,9,8,6,7,3,0};
bubble_sort(arry,sizeof(arry)/sizeof(arry[0]));
for (int i = 0; i < sizeof(arry) / sizeof(arry[0]); i++)
cout << arry[i] << " ";
cout << endl;
return 0;
}
operation result:
Time complexity of bubble sorting method:
Number of comparisons: 1 + 2 +...+N-3 + N-2 + N-1 = (1 + (N-1)) * (N-1) / 2 = N^2/2-N/ 2
Number of exchanges: 1 + 2 +...+N-3 + N-2 + N-1 = (1 + (N-1)) * (N-1) / 2 = N^2/2-N/ 2
So the time complexity of bubbling is (N^2/2-N/2) + (N^2/2-N/2) = N^2-N
The final time complexity is: O(N^2)