Tuesday 25 August 2015

Java Practice 9

Write a program to implement quick sort?
  1. public class QuickSort
  2.  {
  3. private int array[];
  4. private int length;

  5. public void sort(int[] inputArr) {

  6. if (inputArr == null || inputArr.length == 0) {
  7. return;
  8. }
  9. this.array = inputArr;
  10. length = inputArr.length;
  11. quickSort(0, length - 1);
  12. }

  13. private void quickSort(int lowerIndex, int higherIndex) {

  14. int i = lowerIndex;
  15. int j = higherIndex;
  16. // calculate pivot number, I am taking pivot as middle index number
  17. int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
  18. // Divide into two arrays
  19. while (i <= j) {
  20. /**
  21. * In each iteration, we will identify a number from left side which
  22. * is greater then the pivot value, and also we will identify a number
  23. * from right side which is less then the pivot value. Once the search
  24. * is done, then we exchange both numbers.
  25. */
  26. while (array[i] < pivot) {
  27. i++;
  28. }
  29. while (array[j] > pivot) {
  30. j--;
  31. }
  32. if (i <= j) {
  33. exchangeNumbers(i, j);
  34. //move index to next position on both sides
  35. i++;
  36. j--;
  37. }
  38. }
  39. // call quickSort() method recursively
  40. if (lowerIndex < j)
  41. quickSort(lowerIndex, j);
  42. if (i < higherIndex)
  43. quickSort(i, higherIndex);
  44. }

  45. private void exchangeNumbers(int i, int j) {
  46. int temp = array[i];
  47. array[i] = array[j];
  48. array[j] = temp;
  49. }

  50. public static void main(String a[]){

  51. QuickSort sorter = new QuickSort();
  52. int[] input = {24,2,45,20,56,75,2,56,99,53,12};
  53. sorter.sort(input);
  54. for(int i:input){
  55. System.out.print(i);
  56. System.out.print(" ");
  57. }
  58. }
  59. }