Quick Sort is a divide-and-conquer algorithm that efficiently sorts an array by selecting a pivot element and partitioning the other elements into two groups:
This process is recursively applied to both groups until the entire array is sorted.
Scenario | Time Complexity | Description |
---|---|---|
Best Case | O(n log n) | Occurs when the pivot divides the array into two nearly equal parts. |
Average Case | O(n log n) | Typically achieved with balanced partitions during recursion. |
Worst Case | O(n²) | Happens when the pivot is the smallest or largest element each time, leading to highly unbalanced partitions (e.g., already sorted array). |
Quick Sort remains a popular choice due to its average-case efficiency, despite potential pitfalls with worst-case performance.
https://drawtocode.vercel.app/problems/quick-sort-algorithm
Loading component...
Loading component...
INPUT: [8, 3, 5, 4, 2, 7, 6, 1]
OUTPUT: [1, 2, 3, 4, 5, 6, 7, 8]
public static void main(String args[]){
int arr[] = { 12, 11, 13, 5, 6, 7 };
System.out.println("Given array is");
printArray(arr);
quickSort( arr, 0, 5);
System.out.println("\nSorted array is");
printArray(arr);
}//function end
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}//If End
}//function end
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}//If End
}//Loop End
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}//function end
static void printArray(int[] arr){
for (int val : arr) {
System.out.print(val + " ");
}//Loop End
System.out.println();
} // Function End