# Thread: Need help with quick sort method

1. Member Join Date
Jan 2011
Posts
24
Rep Power
0

## Need help with quick sort method

I have to right a quick sort method that will sort an array of random integers from smallest to largest. I wrote the method already but I can only figure out how to sort it from largest to smallest. The code does everything I need it to do except that I need the order to be reversed. If someone could show me what I am doing wrong it would be much appreciated.

Thanks

Java Code:
```import java.util.*;

public class QuickSortTest
{

public static void main(String[] args)
{
Random gen=new Random(); int[] a=new int;
int i; for (i=0; i<a.length; i++) a[i]=gen.nextInt(5000)+1;
System.out.println("Initial array:");
for (i=0; i<a.length; i++) System.out.println(a[i] + " ");
System.out.println();
quicksort(a, 0, a.length-1);
System.out.println("Sorted array:");
for (i=0; i<a.length; i++) System.out.println(a[i] + " ");
System.out.println("Done!");
}

public static void quicksort(int[] a, int i,int j)
{
int p;
if(i < j)
{
p = partition (a,i,j);
System.out.println("upper is: " + p);
quicksort (a,i,p-1);
quicksort (a,p+1,j);
}
}

public static int partition(int[] a, int i,int j) // I think that the problem is somewhere in here but I cant figure it out
{
int upper, lower, save;

upper = i; lower = j; save= a[i];
while(upper != lower)
{
while((upper < lower) && (save >= a[lower])) lower--;
if(upper != lower) a[upper]= a[lower];
while((upper < lower) && (save <= a[upper]))
upper++;
if(upper != lower) a[lower]= a[upper];
}
a[upper]=save;
return(upper);
}

}```  Reply With Quote

2. ## Sort in ascending order an array of integers:

Java Code:
```public void sortAscending(int[] myArray, boolean b) {
b? java.util.Arrays.sort(myArray) :
java.util.Arrays.sort(myArray, Collections.reverseOrder());
}```

Usage:

Java Code:
```// sorts in ascending order
sortAscending(arrayOfInt,true);

// sorts in descending order
sortAscending(arrayOfInt,false);```  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•