快速排序的多种思路实现
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了快速排序的多种思路实现相关的知识,希望对你有一定的参考价值。
快速排序的多种思路实现:
两边想中间靠拢:
// 两边想中间靠拢,当a[left]<key a[right]>key时,两者交换 int PartSortBothSize(int *a, int left, int right) { assert(a != NULL); int key = a[right]; int begin = left; int end = right - 1; while (begin < end) { while (begin<end && (a[begin]<=key)) { ++begin; } while (begin<end&&(a[end]>=key)) { --end; } if (begin < end) { swap(a[begin], a[end]); } } if (a[begin]>a[right]) { swap(a[begin], a[right]); return begin; } return right; }
挖坑法:
// 挖坑法left right是坑 a[left]>key 时 将a[left]放到right位置,a[right]<key时,将a[right]放到left位置 int PartSortPotholing(int *a, int left, int right) { assert(a != NULL); int key = a[right]; int begin = left; int end = right; while (left<right) { while (left<right&&a[left] <= key) { left++; } if (left < right) { a[right] = a[left]; right--; } while (left<right&&a[right] >= key) { right--; } if (left < right) { a[left] = a[right]; left++; } } a[left] = key; return left; }
顺向
//顺向 //left、right从左向右走,当a[left]<key时,left停止,当a[right]>key,right停止,交换两者对应的值 int PartSortBothRight(int *a, int left, int right) { assert(a != NULL); int key = a[right]; int prev = left; while (a[left] < key)//当开始的数字比key小移动left、prev { left++; prev++; } while (left < right) { while (left < right&&a[left] >= key) { left++; } while (left < right&&a[prev] <= key) { prev++; } if (left < right) { swap(a[left], a[prev]); left++; prev++; } } swap(a[prev], a[left]); return prev; }
调用函数:
void _QuickSort(int *a, int left,int right) { assert(a != NULL); if (left >= right) { return; } //int div = PartSortBothSize(a, left, right); //int div = PartSortPotholing(a, left, right); int div = PartSortBothRight(a, left, right); if (div > 0) { _QuickSort(a, left, div - 1); } if (div < right - 1) { _QuickSort(a, div + 1, right); } } void QuickSort(int *a, size_t size) { assert(a != NULL); if (size > 1) { _QuickSort(a, 0, size - 1); } }
test:
int a4[] = { 0, 5, 2, 1, 5, 5, 7, 8, 5, 6, 9, 4, 3, 5, -2, -4, -1 };
以上是关于快速排序的多种思路实现的主要内容,如果未能解决你的问题,请参考以下文章