0

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. 
5
  • 2
    In a case-sensitive search T sorts before b. Commented Sep 25, 2020 at 3:22
  • 2
    Use stricmp() if you want case-insensitive comparison. Commented Sep 25, 2020 at 3:26
  • 1
    It looks like you want upper case and lower case to be interchangeable (a case insensitive search) for Windows the furnction is stricmp() and for Unix it is strcasecmp() Commented Sep 25, 2020 at 3:26
  • Great to know thank you Commented Sep 25, 2020 at 3:37
  • Where is sort coming from? Commented Sep 29, 2020 at 2:03

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I understand that "Nothing" is a valid answer to that question but he did give an expected output so it would help future people looking at this question if you would offer a suggestion of how to achieve the expected output.
@JerryJeremiah I've added a paragraph that does exactly that, but the OP's big problem is simply that he/she didn't understand why the output happened. Knowing that 't' is different from 'T' should help significantly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.