- //C++实现冒泡排序
- #include <iostream>
- using namespace std;
- void print(int* pData, int count){
- for (int i = 0; i< count; i++) {
- cout << pData[i] << " ";
- }
- cout << endl;
- }
- void BubbleSort(int* pData, int count)
- {
- int temp;
- for (int i = 1; i < count; i++)
- {
- for (int j = count - 1; j >= i; j--)
- {
- if (pData[j] < pData[j - 1])
- {
- temp = pData[j - 1];
- pData[j - 1] = pData[j];
- pData[j] = temp;
- }
- }
- cout << "The "<< i <<" round:" << endl;
- print(pData, count);
- cout << "----------------------------" << endl;
- }
- }
- int main()
- {
- int data[] = {10, 8, 9, 7, 4, 5};
- BubbleSort(data, 6);
- cout << "The sort result:" << endl;
- print(data, 6);
- return 0;
- }
运行结果:
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