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;
}
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;
}