冒泡排序C++实现

来源:互联网 发布:python 自动登录签到 编辑:程序博客网 时间:2024/06/08 17:17
  1. //C++实现冒泡排序  
  2.   
  3. #include <iostream>  
  4. using namespace std;  
  5.   
  6. void print(int* pData, int count){  
  7.     for (int i = 0; i< count; i++) {  
  8.         cout << pData[i] << " ";  
  9.     }  
  10.     cout << endl;  
  11. }  
  12.   
  13. void BubbleSort(int* pData, int count)  
  14. {  
  15.     int temp;  
  16.     for (int i = 1; i < count; i++)  
  17.     {  
  18.         for (int j = count - 1; j >= i; j--)  
  19.         {  
  20.             if (pData[j] < pData[j - 1])  
  21.             {  
  22.                 temp = pData[j - 1];  
  23.                 pData[j - 1] = pData[j];  
  24.                 pData[j] = temp;  
  25.             }  
  26.         }  
  27.         cout << "The "<< i <<" round:" << endl;  
  28.         print(pData, count);  
  29.         cout << "----------------------------" << endl;  
  30.     }  
  31. }  
  32.   
  33. int main()  
  34. {  
  35.     int data[] = {10, 8, 9, 7, 4, 5};  
  36.     BubbleSort(data, 6);  
  37.     cout << "The sort result:" << endl;  
  38.     print(data, 6);  
  39.     return 0;  
  40. }  

运行结果:

The 1 round:
4 10 8 9 7 5 
----------------------------
The 2 round:
4 5 10 8 9 7 
----------------------------
The 3 round:
4 5 7 10 8 9 
----------------------------
The 4 round:
4 5 7 8 10 9 
----------------------------
The 5 round:
4 5 7 8 9 10 
----------------------------
The sort result:
4 5 7 8 9 10 

0 0
原创粉丝点击