Guest User

Untitled

a guest
May 12th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.80 KB | None | 0 0
  1. public class Sorter
  2. {
  3.     //Swap helper method.
  4.     public static void swap(int [] items, int index_one, int index_two)
  5.     {
  6.         int temp = items[index_one];
  7.         items[index_one] = items[index_two];
  8.         items[index_two] = temp;
  9.     }
  10.    
  11.     //Overloaded method name.
  12.     public static void quicksort(int [] nums)
  13.     {
  14.         quicksort(nums, 0, nums.length - 1);
  15.     }
  16.    
  17.     //Sorter recursive method, items[segment_begining] used as pivot value.
  18.     public static void quicksort(int [] items, int segment_begining, int segment_end)
  19.     {
  20.         if(segment_end - segment_begining >= 2)                     //Do if length of the segment is more than or equal to two.
  21.         {      
  22.             int boundary = segment_begining;                        //Index which will which will separate portions of array.
  23.             int iterator = boundary + 1;                            //Index which will be used to iterate and swap.
  24.            
  25.             while(iterator <= segment_end)                          //Do for as long as iterator hasn't reached the end of segment.
  26.             {
  27.                 if(items[iterator] <= items[segment_begining])      //If number at [iterator] is less than or equal to the number at the [segment_beginning], the pivot.
  28.                 {
  29.                     swap(items, boundary + 1, iterator);            //Swap number at index one more than [boundary] and [iterator].
  30.                     boundary++;                                     //Increment boundary to mark new position of the sorted segment.
  31.                 }
  32.  
  33.                 iterator++;                                         //Increment iterator, move to the next element.
  34.             }
  35.            
  36.             swap(items, boundary, segment_begining);                //Swap [boundary] with [segment_beginning] in order to move pivot to correct index.
  37.             quicksort(items, boundary + 1, segment_end);            //Pivot value at correct index ..x<pivot<y.., do the recursive calls.
  38.             quicksort(items, segment_begining, boundary - 1);       //Sort items at less than pivot index and more than pivot index.                                                                    //Sort items at more than pivot index.
  39.         }                                          
  40.     }
  41. }
Add Comment
Please, Sign In to add comment