insertSort,quickSort,mergeSort
2015-11-27 19:41
477 查看
http://blog.csdn.net/onlyou2030/article/details/48108573已经包含了插入排序。
下面是STL排序实现,省去了边界判断,在大量数据的情况下,影响是可观的。
当然时间复杂度:O(n^2)
下面是STL的快速排序,省去了边界判断。
时间复杂度:O(nlgn)
下面附上归并排序:
时间复杂度:O(nlgn)
优点:实现简单,概念简单
缺点:merge过程需要额外的内存。(其实现过程略)
注:上面的方法都用到两个指针,为我们的解带来较大的优化。
下面是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); }
注:上面的方法都用到两个指针,为我们的解带来较大的优化。
相关文章推荐
- UIText光标用法
- android 如何获得系统权限 android.uid.system
- UI图片轮转器
- UI第十三天: 标签视图
- 通过request读取所有参数的练习
- ae
- iOS学习之TableView03自定义UITableViewCell
- Check if KeyValuePair exists with LINQ's FirstOrDefault
- Android NDK学习之二. ndk-build使用
- ios学习--iphone NSURLRequest NSMutableURLRequest 数据请求相关
- UIImageView的使用
- 纯代码实现布局的UIViewController跳转到带storyboard布局的UIViewController
- uva 1626——Brackets sequence
- 验证组件——FluentValidation
- weka cfsSubsetEvalue.java 中文注释
- 关于UITableView 中两个困惑的问题
- 利用UITextField自定义搜索栏,实现中文输入过程中字母的搜索功能
- Selenium webdriver 学习笔记(三) - 基本UI控件操作
- leetcode之路051 N-Queens
- 23设计模式之建造者模式(Builder)