快速排序(分治算法)
核心思想:一趟快排,是把比候选元素x大的元素交换到x的右边,把比候选元素x小的元素交换到x的左边。
如:{34, 7, 16, 31, 26, 49, 11, 8, 1}第一趟快排后得到的结果为{1, 7, 16, 31, 26, 8, 11, 34, 49}。
一趟快排后,将数分成两组,左边比x小,右边比x大。则可以对左右分别进行快排,用分治算法的思想。
#include <stdio.h>
#include <utility>
int partition(int * array, int start, int end)
{
int comp = array[start];
while (start < end)
{
while (array[end] >= comp && start < end)
{
end--;
}
if (array[end] < comp && start < end)
{
std::swap(array[end], array[start++]);
}
while (array[start] <= comp && start < end)
{
start++;
}
if (array[start] > comp && start < end)
{
std::swap(array[start], array[end--]);
}
}
return start;
}
void quickSort(int * array, int start, int end)
{
if (start < end)
{
int pos = partition(array, start, end);
quickSort(array, start, pos - 1);
quickSort(array, pos + 1, end);
}
}
int main()
{
int arr[] = {34, 7, 16, 31, 26, 49, 11, 8, 1};
quickSort(arr, 0, (sizeof(arr) / sizeof(int)) - 1);
for (int i = 0; i < sizeof(arr) / sizeof(int); i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}