冒泡算法C++模版
此算法乃复习数据结构用,不喜勿喷。。
#include <iostream> #include <ctime> using namespace std; template<typename T> void bubbleSort(T a[], int order, int length) { switch (order) { case 0: for (int i = 0; i < length; i++) { for (int j = 1; j < length; j++) { if (a[j-1] > a[j]) { swap(a[j-1], a[j]); } } } break; case 1: for (int i = 0; i < length; i++) { for (int j = 1; j < length; j++) { if (a[j-1] < a[j]) { swap(a[j-1], a[j]); } } } break; default: break; } } int main() { srand(unsigned(time(NULL)));//set 种子 int n =100; int a[100]; //产生随即数组 for(int i = 0; i < n; i++) { a[i] = rand()%100; // a[i] = 100-i*1.2; } bubbleSort(a, 1, n); for(int i = 0; i < n; i++) cout << a[i] << " "; cout << endl; bubbleSort(a, 0, n); for(int i = 0; i < n; i++) cout << a[i] << " "; cout << endl; return 0; }