演算法 - 交換排序(C++)
阿新 • • 發佈:2018-11-04
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
/*SwapSort.cpp - by Chimomo在程式設計中,交換排序是基本排序方法的一種。所謂交換,就是根據序列中兩個記錄鍵值的比較結果來對換這兩個記錄在序列中的位置,交換排序的特點是:將鍵值較大的記錄向序列的尾部移動,鍵值較小的記錄向序列的前部移動。*/ #include <iostream>using namespace std;static void SwapSort(int *a, int length){ cout << "In Swap Sort:" << endl; for (int i = 0; i < length - 1; i++) { for (int j = i + 1; j < length; j++) { if (a[i] > a[j]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } cout << "Round " << i + 1 << ": "; for (int i = 0; i < 10; i++) { cout << a[i] << " "; } cout << endl; }}void main(){ int a[10] = { 1, 6, 4, 2, 8, 7, 9, 3, 10, 5 }; cout << "Before Swap Sort:" << endl; for each (int i in a) { cout << i << " "; } cout << endl << endl; SwapSort(a, 10); cout << endl << "After Swap Sort:" << endl; for each (int i in a) { cout << i << " "; } cout << endl;}// Output:/*Before Swap Sort:1 6 4 2 8 7 9 3 10 5In Swap Sort:Round 1: 1 6 4 2 8 7 9 3 10 5Round 2: 1 2 6 4 8 7 9 3 10 5Round 3: 1 2 3 6 8 7 9 4 10 5Round 4: 1 2 3 4 8 7 9 6 10 5Round 5: 1 2 3 4 5 8 9 7 10 6Round 6: 1 2 3 4 5 6 9 8 10 7Round 7: 1 2 3 4 5 6 7 9 10 8Round 8: 1 2 3 4 5 6 7 8 10 9Round 9: 1 2 3 4 5 6 7 8 9 10After Swap Sort:1 2 3 4 5 6 7 8 9 10*/