写一个快速排序C++代码
时间: 2023-03-13 07:42:18 浏览: 107
void quickSort(int array[], int start, int end)
{
if (start < end)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(array, start, end);
// Separately sort elements before
// partition and after partition
quickSort(array, start, pi - 1);
quickSort(array, pi + 1, end);
}
}
// This function takes last element as pivot, places
// the pivot element at its correct position in sorted
// array, and places all smaller (smaller than pivot)
// to left of pivot and all greater elements to right
// of pivot
int partition (int array[], int start, int end)
{
int pivot = array[end]; // pivot
int i = (start - 1); // Index of smaller element
for (int j = start; j <= end- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (array[j] <= pivot)
{
i++; // increment index of smaller element
swap(&array[i], &array[j]);
}
}
swap(&array[i + 1], &array[end]);
return (i + 1);
} void swap(int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
}
阅读全文