I'm trying to sort this array in order on C and I'm not getting it right. What I'm doing wrong? The sorted array is wrong, it should be displayed in the below order:
0: boy
1: is
2: right
3: sitting
4: The
5: there.
Thank you all!
int n = sizeof(arr) / sizeof(arr[0]);
int i;
// Print the given array
printf("Given array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
// Sort the array
sort(arr, n);
// Print the sorted array
printf("\nSorted array is\n");
for (i = 0; i < n; i++)
printf("%d: %s \n", i, arr[i]);
return 0;
}
Output:
Sorted array is
The
boy
is
right
sitting
there.
What I'm doing wrong?
Nothing. Your code works fine.
A good way to debug this would be to print the value of, say, the first character of each word. That would show you the value of 'T', 'b', etc., and you'd see that A-Z have lower values than a-z.
Looking at it another way, if you want the words to print in the order given at the top of your question, you're going to have to sort them so that they're not in ASCII order. You'll need to come up with a compare
function that considers 'T' and 't' to be the same.