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
58 changes: 58 additions & 0 deletions quicksort.java
Original file line number Diff line number Diff line change
@@ -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);
}
}