Quick Sort

mail@pastecode.io avatar
unknown
plain_text
a year ago
749 B
5
Indexable
// Quick Sort
package abc;

public class QuickSort {
	public static void main(String[] args) {
		int[] arr = { 12, 11, 13, 5, 6, 7 };
		int n = arr.length;
		quickSort(arr, 0, n - 1);
		for (int i = 0; i < n; i++)
			System.out.print(arr[i] + " ");
	}
	
	public static void quickSort(int[] arr, int l, int pivot){
		if(l<pivot){
			int p = partition(arr, l, pivot);
			quickSort(arr, l, p-1);
			quickSort(arr, p+1, pivot);
		}
	}
	
	public static int partition(int[] arr, int l, int pivot) {
		int x = arr[pivot];
		int i = l-1;
		for(int j=l; j<=pivot-1; j++){
			if(arr[j]<=x){
				i++;
				int tmp = arr[j];
				arr[j] = arr[i];
				arr[i] = tmp;
			}
		}
		
		int tmp = arr[i+1];
		arr[i+1] = arr[pivot];
		arr[pivot] = tmp;
		return i+1;
	}
}