I am using quick sort algorithm to sort the strings in a 2D array. It works for most of the case but I don't know why the code doesn't work for this case. I had look through many similar questions about quick sort in SO but I still can't figure out what is the problem.
Expected output:
Apple
London
Switch
Table
The
Actual Output:
Apple
London
Table
Switch
The
Here's my code:
#include <stdio.h>
#include <string.h>
void quickSort(char arr[][20], int left, int right);
int main(void)
{
int i;
char str[][20] = { "Table", "Apple", "The", "Switch", "London"};
printf("Before:\n");
for(i=0; i<5; i++) {
printf("%s\n", str[i]);
}
printf("\n");
quickSort(str, 0, 4);
printf("After sort:\n");
for(i=0; i<5; i++) {
printf("%s\n", str[i]);
}
return 0;
}
void quickSort(char arr[][20], int left, int right)
{
int i, j;
char *x;
char tmp[20];
i = left;
j = right;
x = arr[(left + (right - left)) / 2];
while(i <= j)
{
while((strcmp(arr[i],x) < 0) && (i <= right) && (j > i)) {
i++;
}
while((strcmp(arr[j],x) > 0) && (j >= left) && (j >= i)) {
j--;
}
if(i <= j) {
strcpy(tmp, arr[i]);
strcpy(arr[i], arr[j]);
strcpy(arr[j], tmp);
i++;
j--;
}
}
if(left < j) {
quickSort(arr, left, j);
}
if(i < right) {
quickSort(arr, i, right);
}
}
x = arr[(left + (right - left)) / 2];looks weird. You only keep a pointer to a string while later you copy the strings. And I cannot remember seeing a line like that in common implementations... Looks like you should rewrite yours...x = arr[(left + right) / 2];at first, but then I found some codes using this insteadstrcpyit to make sure that the pointed data is not altered.