快排的兩種寫法,兩種寫法

來源:互聯網
上載者:User

快排的兩種寫法,兩種寫法
快排方法一:



附:全代碼實現

#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;}


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.