快排的两种写法
Posted mfmdaoyou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了快排的两种写法相关的知识,希望对你有一定的参考价值。
快排方法一:
附:全代码实现
#include<iostream> #include<assert.h> using namespace std; int OnceSort(int *a, int left, int right) { int i = 0; int middle = right; right -= 1; while (left < right) { //left找大于middle的数 while (left < right && *(a + left) <= *(a + middle)) left++; //right找小于middle的数 while (left < right && *(a + right) > *(a + middle)) right--; if (left < right) { swap(*(a + left), *(a + right)); } else { break; } } if (*(a + left) < *(a + middle)) { i = left + 1; } else { i = left; } while (i < middle) { swap(*(a + middle - 1), *(a + middle)); middle--; } return i; } void QuickSort(int* a, int left, int right) { assert(a); int middle = 0; if (left < right) { middle = OnceSort(a, left, right); QuickSort(a, left, middle - 1); QuickSort(a, middle + 1, right); } } int main() { // int a[] = { 6, 5, 4, 1, 4, 2, 4, 3 }; int a[] = { 9, 9, 9, 7, 7, 7, 8, 8, 8, 3, 2, 1, 8, 6 }; QuickSort(a, 0, sizeof(a) / sizeof(a[0]) - 1); return 0; }
快排方法二:
代码实现,下附:
#include<iostream> using namespace std; int onceSort(int a[], int left, int right) { int key = a[left]; while (left < right) { while (left < right && (*(a + right) >= key)) { right--; } if (left < right && (*(a + right) < key)) swap(*(a + right), *(a + left)); while (left < right && (*(a + left) < key)) { left++; } if (left < right && (*(a + left) >= key)) swap(*(a + left), *(a + right)); } a[left] = key; return left; } void QuickSort(int a[], int left, int right) { int middle = 0; if (left < right) { middle = onceSort(a, left, right); QuickSort(a, left, middle - 1); QuickSort(a, middle + 1, right); } } int main() { int a[] = {2,1,4,3,8,7,5,6,4,4,4,4,4}; QuickSort(a, 0, sizeof(a) / sizeof(a[0]) - 1); return 0; }
以上是关于快排的两种写法的主要内容,如果未能解决你的问题,请参考以下文章
排序算法:堆排,快排的实现(快排的三种实现方法以及快排的优化)
排序算法:堆排,快排的实现(快排的三种实现方法以及快排的优化)