Advertisement
laviniatache

Untitled

Nov 20th, 2014
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3.  
  4. public class QuickSort {
  5.     public static int N = 20;
  6.     public static int[] sequence = new int[N];
  7.    
  8.     public static void QuickSort(int left, int right){
  9.         if( right - left <= 0){
  10.             return;
  11.         }
  12.         else{
  13.             Random rand = new Random();
  14.             int pivotIndex = left + rand.nextInt(right - left + 1);
  15.             swap(pivotIndex, right);
  16.            
  17.             int pivot = sequence[right];
  18.             int partition = partitionInt(left,right,pivot);
  19.             QuickSort(left, partition -1);
  20.             QuickSort(partition+1, right);
  21.         }
  22.     }
  23.  
  24.     private static void swap(int d1, int d2) {
  25.         int aux = sequence[d1];
  26.             sequence[d1] = sequence[d2];
  27.             sequence[d2] = aux;
  28.        
  29.     }
  30.  
  31.     private static int partitionInt(int left, int right, int pivot) {
  32.         int leftPtr = left;
  33.         int rightPtr = right;
  34.  
  35.         while(leftPtr <= rightPtr){
  36.             while(right > 0 && sequence[right] > pivot){
  37.                 right--;
  38.             }
  39.             while(sequence[left] < pivot){
  40.                 left++;
  41.             }
  42.             if( leftPtr >= rightPtr ){
  43.                 swap(sequence[leftPtr], sequence[rightPtr]);
  44.                 left++;
  45.                 right--;
  46.             }
  47.         }
  48.         swap(sequence[left],sequence[right]);
  49.         return leftPtr;
  50.     }
  51.     static void printSequence(int[] sorted_sequence)
  52.     {
  53.         for (int i = 0; i < sorted_sequence.length; i++)
  54.             System.out.print(sorted_sequence[i] + " ");
  55.     }
  56.    
  57.     public static void main(String args[])
  58.     {
  59.         System.out
  60.                 .println("Sorting of randomly generated numbers using RANDOMIZED QUICK SORT");
  61.         Random random = new Random();
  62.  
  63.         for (int i = 0; i < N; i++)
  64.             sequence[i] = Math.abs(random.nextInt(100));
  65.  
  66.         System.out.println("\nOriginal Sequence: ");
  67.         printSequence(sequence);
  68.         System.out.println("\nSorted Sequence: ");
  69.         QuickSort(0, N - 1);
  70.         printSequence(sequence);
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement