c++ 基本的排序算法

冒泡排序

[cpp]  view plain  copy
  1. /*冒泡排序*/  
  2. /*冒泡排序思想: 
  3.  * 1)对数组中各数据,依次比较相邻两个元素的大小 
  4.  * 2)如果前面的数据大于后面的数据,交换这两个数据,经过一轮的多次比较排序后,就可以把最小的数据排好 
  5.  * 3)然后让剩下的数据逐次进行比较 
  6.  * */  
  7. #include "iostream"  
  8. using namespace std;  
  9. #define N 15  
  10. void bubbleSort(int a[],int n)  
  11. {  
  12.     int temp;  
  13.     for(int i=0;i<n;i++)  
  14.     {  
  15.         //for(int j=n-1;j>i;j--)//这条和下一条是一个意思  
  16.         for(int j=i+1;j<n;j++)  
  17.         {  
  18.             if(a[j-1]>a[j])  
  19.             {  
  20.                 temp = a[j-1];  
  21.                 a[j-1] = a[j];  
  22.                 a[j]=temp;  
  23.             }  
  24.         }  
  25.     }  
  26.     cout<<"已排序"<<endl;  
  27. }  
  28. int main()  
  29. {  
  30.     int num[N];  
  31.     srand(time(NULL));  
  32.     for(int i=0;i<N;i++)  
  33.     {  
  34.         num[i]=rand()%100;  
  35.     }  
  36.     //show the nums  
  37.     for(int i=0;i<N;i++)  
  38.     {  
  39.         cout<<num[i]<<" ";  
  40.     }  
  41.     cout<<endl;  
  42.   
  43.     bubbleSort(num,N);  
  44.   
  45.     //show the nums  
  46.     for(int i=0;i<N;i++)  
  47.     {  
  48.         cout<<num[i]<<" ";  
  49.     }  
  50.     cout<<endl;  
  51.   
  52.   
  53.     return 0;  
  54. }  


直接选择排序

[cpp]  view plain  copy
  1. /*选择排序*/  
  2. /*选择排序思想 
  3.  * 1)首先选择1个最小的元素,将其与位于第1个位置的数据交换 
  4.  * 2)在剩余的N-1个元素中选择次小的一个元素,与位于第2个位置的数据交换 
  5.  * 3)依次,交换排序*/  
  6. #include "iostream"  
  7. using namespace std;  
  8. #define N 15  
  9. void selectSort(int a[],int n)  
  10. {  
  11.     int temp;  
  12.     int min;  
  13.     int index = -1;  
  14.     for(int i=0;i<n;i++)  
  15.     {  
  16.         min= a[i];  
  17.         for(int j=i;j<n;j++)  
  18.         {  
  19.             if(min>a[j])  
  20.             {  
  21.                 min = a[j];  
  22.                 index = j;  
  23.             }  
  24.         }  
  25.         if(index != -1)  
  26.         {  
  27.             temp = a[i];  
  28.             a[i]=a[index];  
  29.             a[index] = temp;  
  30.         }  
  31.     }  
  32. }  
  33. int main()  
  34. {  
  35.     int num[N];  
  36.     srand(time(NULL));  
  37.     for(int i=0;i<N;i++)  
  38.     {  
  39.         num[i]=rand()%100;  
  40.     }  
  41.     //show the nums  
  42.     for(int i=0;i<N;i++)  
  43.     {  
  44.         cout<<num[i]<<" ";  
  45.     }  
  46.     cout<<endl;  
  47.   
  48.     selectSort(num,N);  
  49.     //show the nums  
  50.     for(int i=0;i<N;i++)  
  51.     {  
  52.         cout<<num[i]<<" ";  
  53.     }  
  54.     cout<<endl;  
  55. }  

猜你喜欢

转载自blog.csdn.net/xuefujin/article/details/79701250