Thread: QuickSort Char Array/String (Alphabetical order)

  1. #1
    Registered User
    Join Date
    Feb 2013
    Posts
    33

    QuickSort Char Array/String (Alphabetical order)

    Currently, I'm implementing a quick sort algorithm to sort a char array of words, so that they're in alphabetical order. I'm just having trouble with it getting to actually run..I'm still a noob to C programming, so please bare with me!

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>
    #include <limits.h>
    #include <stdio.h>
    
    void quickSort(char word[], int length);
    int sortIt(char word[], int left, int right);
    
    int main(){
    
        char str[] = "banana people cars peanut yellow";
        int length = strlen(str);
    
        quickSort(str, length);
    
        for(int i=0; i<length; i++){
            printf("%s ", str[i]);
        }
    
        return 0;
    }
    
    void quickSort(char word[], int length){
        sortIt(word, 0, length-1);
    }
    
    
    int sortIt(char word[], int left, int right){
    
        char *mid = word[(left+right)/2]; //point to the middle
        char temp[right+1];
        int i= left;
        int j = right;
    
        while(i <= j){
    
            //word[i] is less than mid and i<right
            while((strcmp(word[i], mid) < 0) && (i < right)){
                i++;
            }
    
            //word[i] is greater than mid and j>left
            while((strcmp(word[j],mid) > 0) && (j > left)){
                j--;
            }
    
            //swap
            if(i <= j){
                strcpy(temp, word[i]);
                strcpy(word[i], word[j]);
                strcpy(word[j], temp);
                i++;
                j--;
            }
        }
    
        if(left<j){
            sortIt(word,left,j);
        }
        if(i<right){
            sortIt(word, i,right);
        }
    }

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    This:
    Code:
    char str[] = "banana people cars peanut yellow";
    Is ONE string - there's no words here to sort, only letters:
    aaaaabceee, etc.

    If you want words, you need to assign them correctly into your char array.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bubbleSort array string in alphabetical order.
    By martyx in forum C++ Programming
    Replies: 3
    Last Post: 05-14-2010, 11:17 PM
  2. String sort in alphabetical order
    By ThLstN in forum C Programming
    Replies: 6
    Last Post: 01-06-2008, 02:59 AM
  3. Ordering string by alphabetical order
    By Scarvenger in forum C++ Programming
    Replies: 9
    Last Post: 09-16-2006, 08:58 PM
  4. Sorting in Alphabetical order
    By Andre Santiago in forum C Programming
    Replies: 1
    Last Post: 12-13-2002, 06:14 PM
  5. Alphabetical order
    By BubbleMan in forum C++ Programming
    Replies: 1
    Last Post: 10-08-2001, 03:38 PM

Tags for this Thread