Anonymous
Anonymous

Reputation: 93

Quick sort algorithm code

I'm trying to implement a quick sort that sorts numbers and words based on the number value. I can't seem to figure out how to fix the following code to work right.

 if (high!=low&& high>low)//compares hashes and finds the number in the middle. swaps hashes and corresponding words
{

long one=hash[low];
long two=hash[high];
long three = hash[high/2];
    if((one<=two&&one>=three)||(one<=three&&one>=two))
    {
        swap(hash[low], hash[high]);
        swap(copyOfWords[low], copyOfWords[high]);
    }
    else if((three<=one&&three>=two)||(three<=two&&three>=one))
    {

        swap(hash[high/2], hash[high]);
        swap(copyOfWords[high/2], copyOfWords[high]);
    }
    else
    {

    }
    int i=low;
    int j=high-1;
    while(i!=j&&i<j)
    {

        while(hash[i]<hash[high]&&i<j)// find higher numbers and lower numbers then the middlle and swaps them
        {
            i++;
        }
        while(hash[j]>hash[high]&&i<j)
        {
            j--;
        }
        if(i==j||i>j)
        {
        }
        else
        {
            swap(hash[i],hash[j]);
            swap(copyOfWords[i],copyOfWords[j]);
            i++;
            j--;
        }
    }
        swap(hash[i],hash[high]);
    swap(copyOfWords[i], copyOfWords[high]);



    quickSort(low, j-1);//recursive
    quickSort(j+1, high);

}

}

I know the values in hash and copyOfWords are correct because when I use shell sort, it sorts them the right way. for example if there are two words, copyOfWOrds[0]="1994," and copyOfWords[1]="a" then hash[0]=549456039 and hash[1]=197000000, but the sort puts them a 1994, a instead of a 1994,. It causes more problems with more elements. Any help would be appreciated. Thanks

Upvotes: 0

Views: 102

Answers (1)

kuroi neko
kuroi neko

Reputation: 8661

Why don't you go to the quick sort wiki page and see how it's done?

Your code tries to do unnecessary stuffs and eventually trips over its own feet. Keep it simple and it will work.

And Btw Quicksort works very well on arrays, so it's a shame to make one version where the array is hard-coded.

Upvotes: 1

Related Questions