EDIT: code added.
From Wikipedia , the pseudo code for quick sorting in place is as follows:
(Not to mention that they should be trusted blindly)
function quicksort(array)
if length(array) > 1
pivot := select any element of array
left := first index of array
right := last index of array
while left ≤ right
while array[left] < pivot
left := left + 1
while array[right] > pivot
right := right - 1
if left ≤ right
swap array[left] with array[right]
left := left + 1
right := right - 1
quicksort(array from first index to right)
quicksort(array from left to last index)
So you see that it is very similar to your algorithm with a few changes.
while(lower <= upper){
You also need to swap only if lower <= upper, and then update the indexes.
:
quicksort(array from first index to right) {array[0] to array[upper]}
quicksort(array from left to last index) {array[lower] to array[size-1]}
, , while, , .
:
#include <iostream>
#include <cstdlib>
using namespace std;
void quickSort(int array[], int size){
if(size < 2) return;
int pivot, lower, upper, temp;
lower = 0;
upper = size - 1;
pivot = array[rand() % (size)];
while(lower <= upper){
while(array[lower] < pivot){
lower++;
}
while(array[upper] > pivot){
upper--;
}
if ( lower <= upper ) {
temp = array[lower];
array[lower] = array[upper];
array[upper] = temp;
lower++;
upper--;
}
}
quickSort(array, upper+1);
quickSort(&array[lower], size-lower);
}
int main() {
int myArray[] = { 10, 9, 8, 7, 7, 7, 7, 3, 2, 1};
quickSort( myArray, 10 );
for ( int i = 0; i < 10; i++ )
cout << myArray[i] << " ";
return 0;
}
:
1 2 3 7 7 7 7 8 9 10