双向冒泡排序

来源:互联网 发布:用sql语句创建数据库 编辑:程序博客网 时间:2024/06/01 09:48

1、从两边同时进行冒泡排序

一次排出一个最大值和最小值,n/2次,即while(left<right)

#include <iostream>using namespace std;#define dim(x) (sizeof(x)/sizeof(x[0]))void swap(int *x,int *y){int t = *x;*x = *y;*y = t;}//双向冒泡:从数组两端同时进行冒泡void BbSort(int a[],int len){int left = 0,right = len-1;while(left<right){for(int first=left,last=right;first<right;first++,last--){if(a[first]>a[first+1]) //一次排序,排出两个值,一个最小值和一个最大值,第二次排出次小值和次大值swap(&a[first],&a[first+1]);if(a[last]<a[last-1])swap(&a[last],&a[last-1]);}left++;right--;}}void Show(int a[],int len){for(int i=0;i<len;i++){printf("%d ",a[i]);}printf("\n");}int main(){int a[]={5,8,6,0,7,2,4,3,9,1};BbSort(a,dim(a));Show(a,dim(a));system("pause");return 0;}
输出:




0 0