原理:
data 37 96 8 54
比较相邻两元素,第一次把最小的放在最左边
data 8 96 37 54
第二次在剩下的元素取最小的依次存放
data 8 37 96 54
第三次
data 8 37 54 96
排序完成
空间复杂度为O(1),需要一个临时变量交换用
时间复杂度为O(n 2),适合已经部分排序的数组排序
循环次数为n(n-1)/2
data 37 96 8 54
比较相邻两元素,第一次把最小的放在最左边
data 8 96 37 54
第二次在剩下的元素取最小的依次存放
data 8 37 96 54
第三次
data 8 37 54 96
排序完成
空间复杂度为O(1),需要一个临时变量交换用
时间复杂度为O(n 2),适合已经部分排序的数组排序
- static int count = 0; //计算次数
- void Output(int array[], int n)
- {
- printf("%d:/t/t ", count++);
- for (int i=0; i<n; i++)
- {
- printf("%d ", array[i]);
- }
- printf("/n");
- }
- void swap(int &a, int &b)
- {
- printf("%d > %d/n", a, b);
- int temp;
- temp = b;
- b = a;
- a = temp;
- }
- void BubbleSort(int array[], int n)
- {
- for (int i=0; i<n; i++)
- {
- for (int j=i+1; j<n; j++)
- {
- //依次比较,先选出最小的放在最左边
- if (array[i] > array[j])
- {
- swap(array[i], array[j]);
- Output(array, n);
- }
- else
- printf("%d: Do nothing but also do/n", count++);
- }
- }
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- int array[5] = {37,96,8,54,7};
- Output(array, 5);
- BubbleSort(array, 5);
- printf("****************************************************************************/n");
- count = 0;
- int min_array[5] = {1, 2, 3, 4, 5};
- Output(min_array, 5);
- BubbleSort(min_array, 5);
- printf("****************************************************************************/n");
- count = 0;
- int max_array[5] = {5, 4, 3, 2, 1};
- Output(max_array, 5);
- BubbleSort(max_array, 5);
- return 0;
- }