fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. class JavaApplication1 {
  7.  
  8. public static void main(String args[]) {
  9.  
  10. int[] input = { 23, 31, 1, 21, 36, 72};
  11. System.out.println("Before sorting : " + Arrays.toString(input));
  12. quickSort(input); // sort the integer array using quick sort algorithm
  13. System.out.println("After sorting : " + Arrays.toString(input));
  14.  
  15. // input with duplicates
  16. int[] withDuplicates = { 11, 14, 16, 12, 11, 15};
  17. System.out.println("Before sorting : " + Arrays.toString(withDuplicates));
  18. quickSort(withDuplicates); // sort the integer array using quick sort algorithm
  19. System.out.println("After sorting : " + Arrays.toString(withDuplicates));
  20. }
  21.  
  22. /**
  23.  * public method exposed to client, sorts given array using QuickSort
  24.  * Algorithm in Java
  25.  * @param array
  26.  */
  27. public static void quickSort(int[] array) {
  28. if(array.length <= 1) return;
  29. int leftwall = 0;
  30. int rightwall = array.length - 1 ;
  31. int pivot = array[array.length/2];
  32. rechelperquickSort(array,leftwall,rightwall,pivot);
  33. }
  34.  
  35.  
  36. public static void rechelperquickSort(int[] array ,int left , int right , int pivot ){
  37.  
  38. int idx;
  39. idx = left;
  40.  
  41. if(left>=right) return;
  42.  
  43. while(idx<=right){
  44.  
  45. if(pivot > array[idx])swapinarray(array,left++,idx);
  46.  
  47. idx++;
  48. }
  49. if(left >= right) return;
  50. pivot = array[left+1];
  51. rechelperquickSort(array,left+1,right,pivot);
  52. rechelperquickSort(array,0,left,array[left/2]);
  53. }
  54.  
  55. public static void swapinarray(int[] array,int leftelementidx, int rightelementidx){
  56. int tmp = array[leftelementidx];
  57. array[leftelementidx] = array[rightelementidx];
  58. array[rightelementidx] = tmp;
  59. }
  60.  
  61. }
Success #stdin #stdout 0.1s 320256KB
stdin
Standard input is empty
stdout
Before sorting : [23, 31, 1, 21, 36, 72]
After sorting : [1, 21, 23, 31, 36, 72]
Before sorting : [11, 14, 16, 12, 11, 15]
After sorting : [11, 11, 12, 14, 16, 15]