Tutorialspoint
Problem
Solution
Submissions

QuickSort

Certification: Intermediate Level Accuracy: 42.86% Submissions: 14 Points: 10

Write a Java program to implement the QuickSort algorithm. QuickSort is a divide-and-conquer sorting algorithm that works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays according to whether they are less than or greater than the pivot. The sub-arrays are then recursively sorted.

Your task is to implement the QuickSort algorithm to sort an array of integers in ascending order.

Example 1
  • Input: arr = [10, 7, 8, 9, 1, 5]
  • Output: [1, 5, 7, 8, 9, 10]
  • Explanation: Using QuickSort, the array is sorted in ascending order.
Example 2
  • Input: arr = [38, 27, 43, 3, 9, 82, 10]
  • Output: [3, 9, 10, 27, 38, 43, 82]
  • Explanation: The QuickSort algorithm partitions and sorts the array to produce the sorted output.
Constraints
  • 1 <= arr.length <= 10^5
  • -10^9 <= arr[i] <= 10^9
  • All elements in the array are unique
  • Time Complexity: O(n log n) on average, where n is the size of the array
  • Space Complexity: O(log n) for the recursion stack
  • You must implement the basic QuickSort algorithm with partition function
ArraysAlgorithmsIBMTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Implement a partition function that selects a pivot and places it at its correct position
  • Choose a pivot (typically the last element) and move all smaller elements to the left and all greater elements to the right
  • Return the pivot's final position from the partition function
  • Recursively call QuickSort on the sub-arrays before and after the pivot
  • Handle base cases where the sub-array has 0 or 1 elements
  • Be careful with array indices to avoid out-of-bounds errors
  • Consider optimizations like choosing a better pivot or using insertion sort for small arrays

Steps to solve by this approach:

 Step 1: Check if the array has more than one element; if not, it's already sorted.
 Step 2: Choose a pivot element (typically the last element in the array).
 Step 3: Partition the array around the pivot so that elements less than pivot are on the left and elements greater than pivot are on the right.
 Step 4: Track the position where the pivot will end up (partitioning index).
 Step 5: Swap elements that are less than the pivot to the left side of the array.
 Step 6: Place the pivot in its final sorted position by swapping it with the element at the partitioning index.
 Step 7: Recursively apply the same process to the sub-arrays on either side of the pivot until the entire array is sorted.

Submitted Code :