diff --git a/Java/QuickSort.java b/Java/QuickSort.java new file mode 100644 index 0000000..c1df86e --- /dev/null +++ b/Java/QuickSort.java @@ -0,0 +1,52 @@ +public class QuickSort { + + public static void main(String[] args) { + int[] array = {9, 7, 5, 11, 12, 2, 14, 3, 10, 6}; + int n = array.length; + + System.out.println("Original array:"); + printArray(array); + + quickSort(array, 0, n - 1); + + System.out.println("Sorted array:"); + printArray(array); + } + + public static void quickSort(int[] array, int low, int high) { + if (low < high) { + int pivotIndex = partition(array, low, high); + + quickSort(array, low, pivotIndex - 1); + quickSort(array, pivotIndex + 1, high); + } + } + + public static int partition(int[] array, int low, int high) { + int pivot = array[high]; + int i = (low - 1); + + for (int j = low; j <= high - 1; j++) { + if (array[j] < pivot) { + i++; + swap(array, i, j); + } + } + + swap(array, i + 1, high); + return i + 1; + } + + public static void swap(int[] array, int i, int j) { + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + public static void printArray(int[] array) { + for (int num : array) { + System.out.print(num + " "); + } + System.out.println(); + } +}