【原创】双向冒泡排序

//双向冒泡 bubble sort 
#include <iostream>
#include <ctime>
#define MAX 1000
#define N 10
using namespace std;
void bubble(int* a,const int& len);
inline void swap(int& x,int& y);
int main(int argc,char* argv[])
{
      srand((unsigned)time(0));    
      int a[MAX],n[N];   
      for(int i=0;i<MAX;i++)
            a[i]=i;
      for(int i=0;i<N;i++)  //产生一个无序数组 
      {
            int k=rand()%(MAX-i);  
            n[i]=a[k];
            swap(a[k],a[MAX-i]);
            cout <<n[i] <<" ";
      }  
      cout <<endl;
      bubble(n,N);    
      system("pause");
      return 0;
}
 
void bubble(int* a,const int& len)  //双向冒泡排序 
{ 
    int left=0,right=len-1,count=0;
    while(left<right)
    {
        for(int i=0;i<len-1-i;i++)
        {
            int top=i,end=len-1-i; 
            count++;   
            //比较大的数往后移 
            if(a[top]>a[top+1]) swap(a[top],a[top+1]);
            //比较小的数往前移 
            if(a[end]<a[end-1]) swap(a[end],a[end-1]);    
        } 
        left++;
        right--;            
    }
    for(int i=0;i<=len-1;i++)
       cout <<a[i] <<" ";
    cout <<endl <<"循环了:" <<count <<"次" <<endl;
}
 
inline void swap(int& x,int& y) //交换x,y 
{
     int temp=y;
     y=x;
     x=temp;
}
posted @ 2009-11-19 18:23  leukotrichia  阅读(1331)  评论(0编辑  收藏  举报