From 8d239e561c96e67d7c9f8574a76b4b81f33a749e Mon Sep 17 00:00:00 2001 From: Abhinav Singh Date: Wed, 1 Oct 2025 19:50:50 +0530 Subject: [PATCH] added quicksort in java --- quicksort.java | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 quicksort.java diff --git a/quicksort.java b/quicksort.java new file mode 100644 index 0000000..dc60f6e --- /dev/null +++ b/quicksort.java @@ -0,0 +1,58 @@ +public class QuickSort { + + // Function to perform QuickSort + public static void quickSort(int[] arr, int low, int high) { + if (low < high) { + // Partition the array and get pivot index + int pi = partition(arr, low, high); + + // Recursively sort elements before and after partition + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } + } + + // Partition function + private static int partition(int[] arr, int low, int high) { + int pivot = arr[high]; // choosing the last element as pivot + int i = low - 1; // index of smaller element + + for (int j = low; j < high; j++) { + // if current element <= pivot, swap + if (arr[j] <= pivot) { + i++; + // swap arr[i] and arr[j] + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + + // swap pivot into the correct position + int temp = arr[i + 1]; + arr[i + 1] = arr[high]; + arr[high] = temp; + + return i + 1; // return pivot index + } + + // Utility function to print the array + public static void printArray(int[] arr) { + for (int num : arr) { + System.out.print(num + " "); + } + System.out.println(); + } + + // Main method + public static void main(String[] args) { + int[] arr = {10, 7, 8, 9, 1, 5}; + System.out.println("Original Array:"); + printArray(arr); + + quickSort(arr, 0, arr.length - 1); + + System.out.println("Sorted Array:"); + printArray(arr); + } +}