#include <iostream> #include <iomanip> using namespace std; #define _SWAP(x, y) if (x == y){}else x ^= y ^= x ^= y //插入排序 void Insert_sort(int *begin, int *end) { int n; int *p; for (int *pdwCur = begin + 1; pdwCur != end; ++pdwCur) { p = pdwCur; n = *p; for (; p != begin && n < *(p - 1); --p) { *p = *(p - 1); } *p = n; } } //冒泡排序 void Bubble_sort(int *begin, int *end) { for (int *pdwI = begin, *pdwLast = end - 1; pdwI != end; ++pdwI, --pdwLast) for (int *pdwJ = begin; pdwJ != pdwLast; ++pdwJ) { if (*pdwJ > *(pdwJ + 1)) { _SWAP(*pdwJ, *(pdwJ + 1)); } } } //选择排序 void Select_sort(int *begin, int *end) { for (int *pdwI = begin; pdwI != end; ++pdwI) for (int *pdwJ = pdwI + 1; pdwJ != end; ++pdwJ) { if (*pdwI > *pdwJ) { _SWAP(*pdwI, *pdwJ); } } } //快速排序 void Quick_sort(int *begin, int *end) { if (begin >= end) { return; } int *pdwLeft = begin, *pdwRight = end; for (; pdwLeft < pdwRight;) { while (pdwLeft < end && *begin >= *(++pdwLeft)); while (pdwRight > begin && *begin <= *(--pdwRight)); if (pdwLeft < pdwRight) { _SWAP(*pdwLeft, *pdwRight); } } _SWAP(*begin, *pdwRight); Quick_sort(pdwRight + 1, end); Quick_sort(begin, pdwRight); } int main() { int a[][11] = {{6,8,2,9,1,6,5,6,7,3,9},{6,8,2,9,1,6,5,6,7,3,9}, {6,8,2,9,1,6,5,6,7,3,9},{6,8,2,9,1,6,5,6,7,3,9}}; char *info[4] = {"Insert_sort", "Bubble_sort", "Select_sort", "Quick_sort"}; typedef void(*sort_func_t)(int*, int*); sort_func_t sort_f[4] = {Insert_sort, Bubble_sort, Select_sort, Quick_sort}; for (int i = 0; i != 4; ++i) { cout << setw(13) << left << info[i] << " result: "; sort_f[i](a[i], a[i] + sizeof(a[i]) / sizeof(*a[i])); for (int j = 0; j != sizeof(a[i]) / sizeof(*a[i]); ++j) { cout << a[i][j] <<"."; } cout << "/n"; } system("pause"); return 0; } 嗯,我从来都没写过快排,今天看了下算法思路,感觉很容易写出来,可能是因为是递归算法所以比较好写吧。至于什么KMP之流,我是一辈子都不想写。。。