第6章 函式 第4題
阿新 • • 發佈:2019-01-22
題目:
設計一個支援整型、實型和字元型的氣泡排序的函式模板。
程式碼:
//氣泡排序(函式模版) //注意:T只能定義有多種可能型別的值,如i,j只能用int #include <iostream> using namespace std; template <class T> T sort(T a); int main() { const int length = 1000; //可改 char a[length] = {0}; int i, n = 0; cout << "氣泡排序(從小到大)" << endl << endl; cout << "請輸入要排序的資料的數量:"; cin >> n; cout << "請輸入要排序的資料:(彼此之間用空格隔開)"; for (i = 0; i < n; ++i) cin >> a[i]; sort(a); cout << endl << "氣泡排序(從小到大)後的結果為:"; for (i = 0; i < n; ++i) cout << a[i] << " "; cout << endl << endl; system("pause"); return 0; } template <class T> T sort(T a) { int i, j, tmp, len = strlen(a); bool judge; //用氣泡排序從小到大排序,因為它類似於貪婪法 for (j = 1; j <= len - 1; ++j) { judge = false; //重置judge for (i = 0; i < len - j; ++i) { if (a[i] > a[i + 1]) { tmp = a[i]; a[i] = a[i + 1]; a[i + 1] = tmp; judge = true; } } if (judge == false) break; //若本輪中沒有發生交換,則提前退出 } return a; }