Binary TreesBinary Trees36

  1. 1Preorder Traversal of a Binary Tree using Recursion
  2. 2Preorder Traversal of a Binary Tree using Iteration
  3. 3Postorder Traversal of a Binary Tree Using Recursion
  4. 4Postorder Traversal of a Binary Tree using Iteration
  5. 5Level Order Traversal of a Binary Tree using Recursion
  6. 6Level Order Traversal of a Binary Tree using Iteration
  7. 7Reverse Level Order Traversal of a Binary Tree using Iteration
  8. 8Reverse Level Order Traversal of a Binary Tree using Recursion
  9. 9Find Height of a Binary Tree
  10. 10Find Diameter of a Binary Tree
  11. 11Find Mirror of a Binary Tree - Todo
  12. 12Inorder Traversal of a Binary Tree using Recursion
  13. 13Inorder Traversal of a Binary Tree using Iteration
  14. 14Left View of a Binary Tree
  15. 15Right View of a Binary Tree
  16. 16Top View of a Binary Tree
  17. 17Bottom View of a Binary Tree
  18. 18Zigzag Traversal of a Binary Tree
  19. 19Check if a Binary Tree is Balanced
  20. 20Diagonal Traversal of a Binary Tree
  21. 21Boundary Traversal of a Binary Tree
  22. 22Construct a Binary Tree from a String with Bracket Representation
  23. 23Convert a Binary Tree into a Doubly Linked List
  24. 24Convert a Binary Tree into a Sum Tree
  25. 25Find Minimum Swaps Required to Convert a Binary Tree into a BST
  26. 26Check if a Binary Tree is a Sum Tree
  27. 27Check if All Leaf Nodes are at the Same Level in a Binary Tree
  28. 28Lowest Common Ancestor (LCA) in a Binary Tree
  29. 29Solve the Tree Isomorphism Problem
  30. 30Check if a Binary Tree Contains Duplicate Subtrees of Size 2 or More
  31. 31Check if Two Binary Trees are Mirror Images
  32. 32Calculate the Sum of Nodes on the Longest Path from Root to Leaf in a Binary Tree
  33. 33Print All Paths in a Binary Tree with a Given Sum
  34. 34Find the Distance Between Two Nodes in a Binary Tree
  35. 35Find the kth Ancestor of a Node in a Binary Tree
  36. 36Find All Duplicate Subtrees in a Binary Tree

Quick Sort - Algorithm, Visualization, Examples



Problem Statement

Given an array of integers, your task is to sort the array in ascending order using the Quick Sort algorithm.

This algorithm is known for its efficiency in practice and is commonly used in systems where performance is critical.

Examples

Input ArraySorted OutputDescription
[10, 5, 2, 3, 7][2, 3, 5, 7, 10]Normal case with unsorted distinct integers
[5, 5, 5, 5][5, 5, 5, 5]All elements are the same, already sorted
[9, 8, 7, 6, 5][5, 6, 7, 8, 9]Reverse sorted input
[1][1]Single-element array is already sorted
[][]Empty array, nothing to sort
[3, -1, 0, 2][-1, 0, 2, 3]Includes negative numbers
[100, 10, 1000, 1][1, 10, 100, 1000]Wide range of values

Solution

Quick Sort is a clever and efficient way to sort an array by using a strategy called divide-and-conquer. The idea is to choose one element as a pivot and reorganize the array so that:

  • All elements less than the pivot go to its left
  • All elements greater than the pivot go to its right

After this step, the pivot is in its final sorted position. We then apply the same logic to the left and right sides of the pivot recursively.

What Happens in Different Cases?

1. Normal Unsorted Arrays: Quick Sort performs very well and quickly splits the array into smaller parts. Choosing a good pivot (like the middle element or using a random pivot) helps improve efficiency and avoid worst-case performance.

2. Already Sorted or Reverse Sorted Arrays: If the pivot is always the smallest or largest element (like when choosing the first or last), it can lead to unbalanced partitions. This results in poor performance — almost like a slow bubble sort (O(n²)). A better pivot selection strategy (like median-of-three or random) helps overcome this.

3. Duplicate Elements: Quick Sort handles duplicates well if the partitioning logic puts equal elements on either side. Some implementations optimize for this with 3-way partitioning.

4. Small or Trivial Arrays: For arrays with one element or zero elements, the algorithm immediately returns the same array since there's nothing to sort. These are the base cases for the recursion to stop.

5. Arrays with Negative Numbers: Quick Sort treats all numbers equally — positive or negative — so negative numbers are placed correctly based on comparison with the pivot.

Why Quick Sort is Popular

Quick Sort is used in many real-world systems because:

  • It sorts in-place (no extra space like Merge Sort)
  • Its average time complexity is O(n log n), which is optimal for comparison-based sorting
  • It’s easy to implement and can be fine-tuned with optimizations

However, it's important to remember that Quick Sort is not stable (it does not preserve the order of equal elements), and its worst-case performance is O(n²) if poor pivot choices are made.

In practice, a well-implemented Quick Sort is very fast and efficient for most inputs.

Algorithm Steps

  1. Choose a pivot element from the array.
  2. Partition the array so that all elements less than the pivot are on the left, and all greater elements are on the right.
  3. Recursively apply the above steps to the left and right partitions.
  4. Combine the partitions to form a sorted array.

Code

Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    else:
        pivot = arr[len(arr) // 2]
        left = [x for x in arr if x < pivot]
        middle = [x for x in arr if x == pivot]
        right = [x for x in arr if x > pivot]
        return quick_sort(left) + middle + quick_sort(right)

if __name__ == '__main__':
    arr = [6, 3, 8, 2, 7, 4]
    sorted_arr = quick_sort(arr)
    print("Sorted array is:", sorted_arr)


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M