Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions Java/QuickSort.java
Original file line number Diff line number Diff line change
@@ -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();
}
}