#include <iostream> #include <fstream> #include <vector> #include <assert.h> using namespace std; template <class T> void order(vector <T> &a) { int count = a.size(); T temp; for (int i=0;i<count;i++) { for (int j=0;j<count-i-1;j++) { if (a[j]>a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } } template <class T> void order(T arr[],int len) { T temp; for (int i = 0; i < len - 1; i++) for (int j = 0; j < len - 1 - i; j++) if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } int main(void) { //文件排序 ifstream fin("order.txt"); assert(fin); vector<double> a; double temp; while(!fin.eof()) { fin>>temp; a.push_back(temp); } fin.close(); order(a); ofstream fout("order_out.txt"); assert(fout); for (int i = 0; i<a.size(); i++) { fout<<a[i]<<endl; } //数组排序 double arr[] = { 22, 34, 3,289754282,12313,1231424214}; int len = (int) sizeof(arr) / sizeof(*arr); order(arr,len); }
快速排序法(速度最快)
#include<iostream> using namespace std; void quickSort(int s[], int l, int r) { if (l< r) { int i = l, j = r, x = s[l]; while (i < j) { while(i < j && s[j]>= x) j--; if(i < j) s[i++] = s[j]; while(i < j && s[i]< x) i++; if(i < j) s[j--] = s[i]; } s[i] = x; quickSort(s, l, i - 1); quickSort(s, i + 1, r); } } int main() { int array[]={4,5,12,4,6,5,7,1,3,7}; int len=sizeof(array)/sizeof(int); quickSort(array,0,len-1); system("pause"); return 0; }