This blog will soon be merged with

JavaByPatel

which explains each solution in detail, to visit new blog, click JavaByPatel

Wednesday, 24 December 2014

Quick Sort


package sorting;

public class QuickSort {
 public static void main(String[] args) {
  new QuickSort();
 }

 public QuickSort() {
  int[] arr=new int[]{6,1,4,2,3};

  System.out.println("Before Sorting...");
  printArray(arr);
  System.out.println();
  quickSort(arr, 0, arr.length - 1);
  System.out.println("After Sorting...");
  printArray(arr);
  
 }

 private void quickSort(int[] array, int lowerIndex, int higherIndex) {

  int i = lowerIndex;
  int j = higherIndex;
  int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];

  while (i <= j) {
   while (array[i] < pivot) {
    i++;
   }
   while (array[j] > pivot) {
    j--;
   }
   if (i <= j) {
    int tmp = array[i];
    array[i]=array[j];
    array[j]=tmp;
    //move index to next position on both sides
    i++;
    j--;
   }
  }
  if (lowerIndex < j)
   quickSort(array, lowerIndex, j);
  if (i < higherIndex)
   quickSort(array, i, higherIndex);
 }

 private void printArray(int arr[]){
  for (int i = 0; i < arr.length; i++) {
   System.out.print(arr[i] + " ");
  }
 }
}

No comments:

Post a Comment