http://blog.csdn.net/onlyou2030/article/details/48108573已经包含了插入排序。
下面是STL排序实现,省去了边界判断,在大量数据的情况下,影响是可观的。
当然时间复杂度:O(n^2)
#include <iostream> #include <vector> #include <algorithm> using namespace std; int * copy_backward(int * first,int* last,int* result) { while (last != first) *(--result) = *(--last); return result; } void insertSort(int *first, int *last) { for (int *i = first + 1; i != last; ++i) { int value = *i; if (value < *first) //如果小于第一个,直接放到第一个 { copy_backward(first, i, i + 1); *first = value; } else { int *next = i; --next; while (value < *next) { *i = *next; //往后移数据 i = next; --next; } *i = value; } } } int main() { int a[] = { 3, 4, 5, 7, 9, 2, 10, 1, 8, 0 }; insertSort(a, a + 10); //[a,a+10) for (int i = 0; i < 10; ++i) cout << a[i] << " "; cout << endl; return 0; }
下面是STL的快速排序,省去了边界判断。
时间复杂度:O(nlgn)
#include <iostream> #include <vector> #include <algorithm> using namespace std; int median(int a, int b, int c) { if (a < b) if (b < c) return b; else if (a < c) return c; else return a; else if (a < c) return a; else if (b < c) return c; else return b; } int *partition(int *first, int *last, int pivot) { while (1) //当first>=last时,跳出循环 { while (*first < pivot) ++first; --last; //默认是不包括last的,需要--才对应最后一个元素 while (*last > pivot) --last; if (first >= last) return first; //返回值是分割后的右段的第一个位置 swap(*first,*last); //晕,不能像迭代器那样swap(first,last) ++first; //为什么不--last呢,因为前面有--last啊 } } void quickSort(int *first, int *last) { if (first == last || first == last - 1) return; int pivot = median(*first,*(last-1),*((first+(last-first)/2))); int *cut = partition(first,last,pivot); quickSort(first,cut); quickSort(cut,last); } int main() { int a[] = { 3, 4, 5, 7, 9, 2, 10, 1, 8, 0 }; quickSort(a, a + 10); //[a,a+10) for (int *i = a; i < a+10; ++i) cout << *i << " "; cout << endl; return 0; }
下面附上归并排序:
时间复杂度:O(nlgn)
优点:实现简单,概念简单
缺点:merge过程需要额外的内存。(其实现过程略)
void mergeSort(int *first, int *last) { if (first == last || first == last - 1) return; int *mid = first + (last - first) / 2; mergeSort(first, mid); mergeSort(mid, last); merge(first,mid,last); }
注:上面的方法都用到两个指针,为我们的解带来较大的优化。