Sunday 24 January 2016

Java program for quick sort



import java.util.*;
public class QuickSort {
public static void main(String[] args) {
int[] x = { 12, 54, 9, 2, 15, 64, 32 };
System.out.println(Arrays.toString(x));
int low = 0;
int high = x.length - 1;
quickSort(x, low, high);
System.out.println(Arrays.toString(x));
}
public static void quickSort(int[] arr, int low, int high) {
if (arr == null || arr.length == 0)
return;
if (low >= high)
return;
// take pivot
int middle = low + (high - low) / 2;
int pivot = arr[middle];
// left < pivot and right > pivot
int i = low, j = high;
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
// recursively sort two sub parts
if (low < j)
quickSort(arr, low, j);
if (high > i)
quickSort(arr, i, high);
}
}

OUTPUT:-
C:\Users\saty\Desktop>javac QuickSort.java
C:\Users\saty\Desktop>java QuickSort
[12, 54, 9, 2, 15, 64, 32]

[2, 9, 12, 15, 32, 54, 64]

2 comments:

  1. Thank you so much for your guides. You explain better than my teacher. I hope you were my teacher. :)

    ReplyDelete
  2. Thanks a lot for your effort. Nice code

    ReplyDelete