Friday, December 1, 2017

QuickSort Java Program

public class QuickSort {
    private int array[];
    private int length;

    public static void main(String[] args) {
 QuickSort sorter = new QuickSort();
 int[] input = { 24, 2, 45, 20, 56, 75, 2, 56, 99, 53, 12 };
 sorter.sort(input);
 for (int i : input) {
     System.out.print(i);
     System.out.print(" ");
 }

    }

    private void sort(int[] input) {
 if (input == null || input.length == 0)
     return;
 this.array = input;
 length = input.length;
 QSort(0, length - 1);

    }

    private void QSort(int low, int high) {
 int i = low;
 int j = high;

 int pivot = array[low + (high - low) / 2];

 while (i <= j) {

     while (array[i] < pivot) {
  i++;
     }
     while (array[j] > pivot) {
  j--;
     }
     if (i <= j) {
  swap(i, j);
  i++;
  j--;
     }
     if (low < j)
  QSort(low, j);
     if (i < high)
  QSort(i, high);
 }
    }
    private void swap(int low, int high) {
 int temp = array[low];
 array[low] = array[high];
 array[high] = temp;
    }
}

No comments: