Click to See Complete Forum and Search --> : Quick sort ascending/descending


kurent
09-24-2008, 08:55 AM
I'm quite embarrassed, but need to ask. How do I modify the below quick sort algorithm to sort in descening order? :o

I thought I only needed to change both of the "Collator.compare(record[i], mid) < 0)" part so that it goes "> 0", but that doesn't work. :confused:



public String[] quickSort(String[] record, int begin, int end, Collator Collator)
{
String[] tempek = new String[1];
int i = begin;
int j = end;
String mid;

if (end > begin)
{
// Arbitrarily establishing partition element as the midpoint of the array.
mid = record[(begin + end) / 2];

// loop through the array until indices cross
while (i <= j)
{
// find the first element that is greater than or equal to the partition element starting from the left Index.
while ((i < end) && (Collator.compare(record[i], mid) < 0)) // maybe here for descending? but it doesn't work :(
{ i++; }

// find an element that is smaller than or equal to the partition element starting from the right Index.
while ((j > begin) && (Collator.compare(record[j], mid) > 0)) // maybe here for descending? but it doesn't work :(
{ j--; }

// if the indexes have not crossed, swap
if (i <= j)
{
tempek[0] = record[j];
record[j] = record[i];
record[i] = tempek[0];

i++;
j--;
}
}

// If the right index has not reached the left side of array must now sort the left partition.
if (begin < j) quickSort(record, begin, j, Collator);

// If the left index has not reached the right side of array must now sort the right partition.
if (i < end) quickSort(record, i, end, Collator);
}

return record_delo;
}

starheartbeam
10-10-2008, 09:00 AM
Here is a small example of a sort method for descending order. See if this helps you any! If not I will take a look at your code and see what needs to be changed.

public static void selection_sort ( int [ ] array )
{
int i, j, first, temp;
for ( i = array.length - 1; i > 0; i - - )
{
first = 0; //initialize first to the subscript of the first element
for(j = 1; j <= i; j ++) //find smallest element between the positions 1 and i.
{
if( array[ j ] < array[ first ] )
first = j;
}
temp = array[ first ]; //swap smallest element found with one in position i.
array[ first ] = array[ j ];
array[ j ] = temp;
}
}

kurent
10-10-2008, 10:35 AM
Thanks for helping, but I already figured out the problem. I was calling the wrong function in the recursive call. :o

starheartbeam
10-10-2008, 10:38 AM
that is good! As long as it works that is great!