冒泡排序是比较容易理解的一种稳定排序方法,我们将记录关键字的顺序表elem[0……n-1]看作垂直排列,每个记录看作是重量为elem[i]的气泡。根据重气泡不能在轻的气泡上的原则,从上往下扫描,把重气泡下沉,轻气泡上浮。这样,我们便能得到一个有序的顺序表了,具体代码如下:
1 template <typename ElemType> 2 void bubbleSort(ElemType elem[],int len) 3 { 4 if(NULL == elem) 5 return; 6 int i,j,k; 7 ElemType temp; 8 for(i=len-1;i>0;i--) 9 { 10 for(j=0;j<i;j++) 11 { 12 if(elem[j]>elem[j+1]) 13 { 14 temp = elem[j]; 15 elem[j]=elem[j+1]; 16 elem[j+1]=temp; 17 } 18 } 19 } 20 }
下面是测试效果
1 #include<windows.h> 2 #include<iostream> 3 using namespace std; 4 int main() 5 { 6 int arr[10]; 7 srand(unsigned int(time_t(NULL)));//随机数种子 8 for(int i=0;i<10;i++) 9 { 10 arr[i]=rand()%10;//0-10内的整数 11 cout<<arr[i]<<" "; 12 } 13 cout<<endl; 14 long time_start = GetTickCount(); 15 bubbleSort(arr,10); 16 long time_stop = GetTickCount(); 17 for(int i=0;i<10;i++) 18 { 19 cout<<arr[i]<<" "; 20 } 21 cout<<endl; 22 cout<<"Time cost:"<<time_stop - time_start<<endl; 23 return 0; 24 }
数据量小,时间忽略不计!