today I've been working on Quicksort algorithm implementation in C. I thought that I've fully understood the issue, but after few attempts, the results weren't the same as I expected. I ask you for help in finding problem, because I can't find it on myself, I've even tried to look at another implementations in internet, and rewriting my functions, but nothing worked. My code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void swap(int *x, int *y)
{
int temp = *y;
*x = *y;
*y = temp;
}
void printArray(int arr[], int size)
{
for(int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low - 1);
for(int j = low; j <= high-1; j++)
{
if(arr[j] <= pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i+1], &arr[high]);
return(i+1);
}
void quickSort(int arr[], int low, int high)
{
if(low < high)
{
int pi = partition(arr, low, high);
quickSort(arr, low, pi-1);
quickSort(arr, pi + 1, high);
}
}
int main()
{
srand(time(NULL));
int arr[10];
for(int i = 0; i < 10; i++)
{
arr[i] = rand()%200 - 100;
}
printArray(arr, 10);
quickSort(arr, 0, 9);
printArray(arr, 10);
return 0;
}
Examplatory results:
-57 4 -30 -23 25 -67 83 26 -51 14
-67 -67 -51 -67 -51 -51 14 -51 14 14
The only problem with your quick-sort is that the swap function is not implemented correctly.
The correct implementation should be something like:
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
You may be interested in looking at some other quick-sort variant, for that see this.
A humble suggestion: Use Randomized Quick sort: It would also be better if you don't always select the last element as your pivot (what you can do here is just before starting to sort select any random element and then swap it with the last element of your array. Using this strategy you don't have to make much changes in your existing code) This selection of random element as pivot is much better. See this link for more details.