赞
踩
先排数字9,以此比较与交换 然后是数字6
数字1比3小,3比5小 ,所以5不动
以此类推1,3不动
- #include<iostream>
- using namespace std;
-
- #define N 10
-
- void Bubble_Sort(int* arr,int n) //参数为数组和长度
- {
- for (int i = 0; i < n ; i++) {
- for (int j = 0; j < n - i - 1; j++) { //n-i-1是比较次数,每比较一趟就少一次
- if (arr[j] > arr[j + 1]) { //交换arr[j]与arr[j+1]的值
- int temp = arr[j];
- arr[j] = arr[j + 1];
- arr[j + 1] = temp;
- }
- }
- }
- }
-
- int main()
- {
- int arr[N] = { 1,4,6,3,0,2,5,9,8,7 };
- Bubble_Sort(arr, 10);
- for (int i = 0; i < N; i++)
- {
- cout << arr[i] << ",";
- }
- cout << endl;
- return 0;
- }

测试结果:
假设我们现在排序ar[]={1,2,3,4,5,6,7,8,10,9}这组数据,按照上面的排序方式,第一趟排序后将10和9交换已经有序,接下来的8趟排序就是多余的,什么也没做。所以我们可以在交换的地方加一个标记,如果那一趟排序没有交换元素,说明这组数据已经有序,不用再继续下去
- void BubbleSort(int arr[], int len)
- {
- int i = 0;
- int tmp = 0;
- for (i = 0; i < len - 1; i++)//确定排序趟数
- {
- int j = 0;
- int flag = 0;
- for (j = 0; j < len - i - 1; j++)//确定比较次数
- {
- if (arr[j]>arr[j + 1])
- {
- //交换
- tmp = arr[j];
- arr[j] = arr[j + 1];
- arr[j + 1] = tmp;
- flag = 1;//加入标记
- }
- }
- if (flag == 0)//如果没有交换过元素,则已经有序
- {
- return;
- }
- }
- }
-

十大经典算法复杂度及稳定性比较:https://blog.csdn.net/alzzw/article/details/98100378
选择排序:https://blog.csdn.net/alzzw/article/details/97964320
插入排序:https://blog.csdn.net/alzzw/article/details/97967278
快速排序:https://blog.csdn.net/alzzw/article/details/97970371
归并排序:https://blog.csdn.net/alzzw/article/details/98047030
堆排序:https://blog.csdn.net/alzzw/article/details/98087519
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。