Results 1 to 2 of 2
  1. #1
    Get_tanked is offline Member
    Join Date
    Jan 2011
    Rep Power

    Default 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.


    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] + " ");  
    	      quicksort(a, 0, a.length-1);   
    	      System.out.println("Sorted array:");
    	      for (i=0; i<a.length; i++) System.out.println(a[i] + " ");  
    	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]))
    			 if(upper != lower) a[lower]= a[upper];

  2. #2
    ozzyman's Avatar
    ozzyman is offline Senior Member
    Join Date
    Mar 2011
    London, UK
    Blog Entries
    Rep Power


    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());


    Java Code:
    // sorts in ascending order
    // sorts in descending order

Similar Threads

  1. Using a Generic Insertion Sort method
    By in forum New To Java
    Replies: 0
    Last Post: 02-06-2011, 03:08 AM
  2. Quick Sort explanation.
    By hawaiifiver in forum New To Java
    Replies: 4
    Last Post: 03-10-2009, 02:28 AM
  3. Quick sort with median-of-three partitioning
    By Java Tip in forum Algorithms
    Replies: 0
    Last Post: 04-15-2008, 07:40 PM
  4. Simple version of quick sort
    By Java Tip in forum Algorithms
    Replies: 0
    Last Post: 04-15-2008, 07:40 PM
  5. Problem with sort method
    By Albert in forum Advanced Java
    Replies: 2
    Last Post: 07-01-2007, 07:12 PM

Posting Permissions

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