|
| 1 | +package com.learn.datastructure; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class QuickSort { |
| 6 | + |
| 7 | + public static void main(String[] args) { |
| 8 | + int[] arr; |
| 9 | + int size; |
| 10 | + System.out.print("Enter the size of the array: "); |
| 11 | + Scanner sc = new Scanner(System.in); |
| 12 | + size = sc.nextInt(); |
| 13 | + |
| 14 | + arr = new int[size]; |
| 15 | + |
| 16 | + System.out.print("Enter the values of the data set: "); |
| 17 | + for(int i=0; i<size; i++) |
| 18 | + arr[i] = sc.nextInt(); |
| 19 | + |
| 20 | + System.out.print("The data before sorting is: "); |
| 21 | + printData(arr); |
| 22 | + |
| 23 | + quickSort(arr, 0, arr.length-1); |
| 24 | + |
| 25 | + System.out.print("The data after sorting is: "); |
| 26 | + printData(arr); |
| 27 | + } |
| 28 | + |
| 29 | + |
| 30 | + public static int partition(int[] arr, int start, int end) { |
| 31 | + int pivot = arr[end]; |
| 32 | + int pi = start; |
| 33 | + |
| 34 | + for(int i=start; i<end; i++) { |
| 35 | + if(arr[i] <= pivot) { |
| 36 | + // swap(arr[i], pi) |
| 37 | + int temp = arr[i]; |
| 38 | + arr[i] = arr[pi]; |
| 39 | + arr[pi] = temp; |
| 40 | + |
| 41 | + pi++; |
| 42 | + } |
| 43 | + } |
| 44 | + // swap(pi, pivot) |
| 45 | + int temp = arr[pi]; |
| 46 | + arr[pi] = arr[end]; |
| 47 | + arr[end] = temp; |
| 48 | + |
| 49 | + return pi; |
| 50 | + } |
| 51 | + |
| 52 | + public static void quickSort(int[] arr, int start, int end) { |
| 53 | + if(start < end) { |
| 54 | + int pi = partition(arr, start, end); |
| 55 | + quickSort(arr, start, pi-1); |
| 56 | + quickSort(arr, pi+1, end); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + public static void printData(int[] arr) { |
| 61 | + int n = arr.length; |
| 62 | + for (int j : arr) System.out.print(j + " "); |
| 63 | + System.out.println(); |
| 64 | + } |
| 65 | + |
| 66 | + |
| 67 | +} |
| 68 | + |
0 commit comments