From 2c3a084841b73da9f9579371342b46bddd3d78d1 Mon Sep 17 00:00:00 2001 From: pawan bansal Date: Fri, 23 Oct 2020 17:45:34 +0530 Subject: [PATCH] Quick sort in java. (#54) * Quick sort in java. * fixes * lint fixes --- Sorting/quick-sort/quickSort.java | 62 +++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 Sorting/quick-sort/quickSort.java diff --git a/Sorting/quick-sort/quickSort.java b/Sorting/quick-sort/quickSort.java new file mode 100644 index 0000000..7de8785 --- /dev/null +++ b/Sorting/quick-sort/quickSort.java @@ -0,0 +1,62 @@ +import java.io.*; +import java.util.*; + +public class Quick_Sort { + public static void main(String[] args) { + int[] arr = takeinput(); + + // sort the array + Quick_Sort(arr, 0, arr.length - 1); + + // display the array + for (int i = 0; i < arr.length; i++) + System.out.print(arr[i] + " "); + } + + public static int[] takeinput() { + Scanner scn = new Scanner(System.in); + + // input array length + int n = scn.nextInt(); + + int[] arr = new int[n]; + + for (int i = 0; i < arr.length; i++) { + // input array elements + arr[i] = scn.nextInt(); + } + + return arr; + } + + public static void Quick_Sort(int[] arr, int lo, int hi) { + // if low index is higher than high index, simply return + if (lo >= hi) + return; + + // define pivot + int pi = (lo + hi) / 2; + int pivot = arr[pi]; + int left = lo, right = hi; + + while (left <= right) { + while (arr[left] < pivot) + left++; + + while (arr[right] > pivot) + right--; + + if (left <= right) { + // swap the values + int temp = arr[left]; + arr[left] = arr[right]; + arr[right] = temp; + left++; + right--; + } + } + + Quick_Sort(arr, lo, right); + Quick_Sort(arr, left, hi); + } +}