Results 1 to 2 of 2
Thread: Need help with quick sort method
- 03-14-2011, 08:18 AM #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[32]; 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); } }
-
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);
Similar Threads
-
Using a Generic Insertion Sort method
By dubois.ford in forum New To JavaReplies: 0Last Post: 02-06-2011, 03:08 AM -
Quick Sort explanation.
By hawaiifiver in forum New To JavaReplies: 4Last Post: 03-10-2009, 02:28 AM -
Quick sort with median-of-three partitioning
By Java Tip in forum AlgorithmsReplies: 0Last Post: 04-15-2008, 07:40 PM -
Simple version of quick sort
By Java Tip in forum AlgorithmsReplies: 0Last Post: 04-15-2008, 07:40 PM -
Problem with sort method
By Albert in forum Advanced JavaReplies: 2Last Post: 07-01-2007, 07:12 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks