Quick Sort is a renowned and efficient sorting algorithm built upon the divide-and-conquer strategy. Fundamentally, it selects a 'pivot' element from the array and subsequently partitions the other elements into two sub-arrays based on whether they're greater or less than the pivot. Following this, the sub-arrays are sorted through recursive methods. In this guide, we'll walk through the process of implementing the Quick Sort algorithm to sort an array of integers in descending order.
Step-by-step Implementation and Explanation
Partition: The array is sectioned into three segments:
- Elements greater than the pivot.
- The pivot itself.
- Elements less than the pivot.
Recursive Sort: The elements greater than the pivot and those less than the pivot are sorted recursively.
Combine: Arrays of size zero or one act as the base case for the recursion. These arrays don't need sorting.
Java Program for Quick Sort in Descending Order
public class QuickSortDescending {
public static void main(String[] args) {
int[] arr = {10, 80, 30, 90, 40, 50, 70};
System.out.println("Unsorted array:");
printArray(arr);
quickSort(arr, 0, arr.length - 1);
System.out.println("\nSorted array in descending order:");
printArray(arr);
}
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);
}
}
public 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;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return i + 1;
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output:
Unsorted array:
10 80 30 90 40 50 70
Sorted array in descending order:
90 80 70 50 40 30 10
Explanation of the Code:
Related Java Programs on Sorting Algorithms
- Bubble Sort in Ascending Order in Java
- Bubble Sort in Descending Order in Java
- Selection Sort in Ascending Order in Java
- Selection Sort in Descending Order in Java
- Insertion Sort in Ascending Order in Java
- Insertion Sort in Descending Order in Java
- Merge Sort in Ascending Order in Java
- Merge Sort in Descending Order in Java
- Quick Sort in Ascending Order in Java
- Quick Sort in Descending Order in Java
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment