Lintcode - 整数排序
2018-01-30 09:19
274 查看
class Solution { public: /* * @param A: an integer array * @return: */ void sortIntegers(vector<int> &A) { // write your code here //SelectionSort(A); //bubleSort(A); //selectionSort1(A); //insertionSort(A); ComparisonCountingSort(A); } private: /*==================Selection sort======================*/ void SelectionSort(vector<int> &a) { int n = a.size(); for (int i=0; i<n-1; i++) { // 当前从i=0,1,2...开始 int min = i;// 找到从i到末尾的最小元素,和i(也就是第一个元素交换) for (int j=i+1; j<n; j++) { if (a[j] < a[min]) min = j; } swap(a[i], a[min]); } } /*==================buble sort=========================*/ void bubleSort(vector<int> &a) { int n = a.size(); for (int i = 0; i < n-1; i++) { // a[i]和a[i //+1]比较,范围到倒数第二个元素 for (int j = 0; j < n - 1 - i; j++) { // 末尾减去i个已经排列好的 if (a[j] > a[j+1]) { swap(a[j], a[j+1]); } } } } /*==================Insertion Sort=====================*/ void insertionSort(vector<int> &a) { int n = a.size(); for (int i=1; i<n; i++) { // 开始默认0元素已经排序好 int v = a[i]; int j = i-1; while (j>=0 && a[j]>v) { a[j+1] = a[j]; // 后移 j--; } a[j+1] = v; } } /*==================Selection Sort递归方式=====================*/ int findSmallest(vector<int> &a, int start, int end) { int min = start; for (int i = start + 1; i <= end; i++) { if (a[i] < a[min]) min = i; } return min; } void selectionSort1(vector<int> &a, int start, int end) { if (start < end - 1) { swap(a[start], a[findSmallest(a, start, end)]); selectionSort1(a, start + 1, end); } } void selectionSort1(vector<int> &a) { if (a.size() <= 1) return; selectionSort1(a, 0, a.size() - 1); } /*===============ComparisonCountingSort======================*/ // 计数排序 void ComparisonCountingSort(vector<int> &a) { int n = a.size(); int Count ; for (int i=0; i<n; i++) { Count[i] = 0; } for (int i=0; i<n-1; i++) { for (int j=i+1; j<n; j++) { if (a[i] < a[j]) { Count[j] += 1; } else { Count[i] += 1; } } } vector<int> res; res.resize(n); for (int i=0; i<n; i++) { res[Count[i]] = a[i]; } a = res; } };
相关文章推荐
- [LintCode] Sort Integers 整数排序
- LintCode-整数排序 II
- lintcode python代码 463 整数排序
- LintCode_463_整数排序
- LintCode【入门】整数排序
- lintcode 463.整数排序
- 整数排序 II -LintCode
- lintcode 463整数排序 lintcode 464整数排序II
- lintcode 入门 463整数排序
- [LintCode] Sort Integers II 整数排序之二
- 【LintCode 入门】463. 整数排序
- LintCode 464 整数排序 II
- 【LintCode】整数排序II
- lintcode_整数排序 II
- lintcode-464-整数排序 II
- (lintcode)第463题整数排序
- lintcode 整数排序 II | 归并排序(Java)
- lintcode 整数排序 II | 快速排序(Java)
- LintCode 第463题 整数排序
- [LintCode] Sort Integers 整数排序