I’ve a problem with my Quicksort. For some values it works but for other it doesn’t. For example when the first value is smaller than the last it doesn’t work. I don’t know what is wrong. This is code:
#include <stdio.h>
#include <time.h>
#define lenght_max 1000000
int x;
int tablica[lenght_max];
int q;
int Partition(left, right) {
int tmp;
int i;
int j;
i = -1;
j = 0;
x = tablica[right];
i = left - 1;
for(j = left; j < right; j++){
if(tablica[j] <= x) {
i++;
tmp = tablica[i];
tablica[i] = tablica[j];
tablica[j] = tmp;
}
}
return i + 1;
}
void Quicksort(left, right) {
if(left < right){
q = Partition(left, right);
Quicksort(left , q - 1);
Quicksort(q + 1, right);
}
}
int main(void) {
int i;
int temporary;
int left;
int right;
printf("Witaj uzytkowniku. To jest program preferujacy sortowanie szybkie - quicksort.\n");
printf("Podaj, ile liczb chcialbys posortowac: ");
scanf("%i", &temporary);
printf("Podaj liczby do sortowania: \n");
for(i = 0; i < temporary; i++)
scanf("%d", &tablica[i]);
left = 0;
right = temporary - 1;
x = temporary / 2;
Quicksort(left, right);
printf("\nPROCES:\n");
for(i = 0; i < temporary; i++)
printf("%d\n", tablica[i]);
return 0;
}
If I didn’t overlook the problem, it seems to me that you forgot to swap the pivot with the first element grater than the pivot at the end of
Partition. The fix should be as simple as adding:before the
return i + 1;statement insidePartition.