Table of contents
1.
Introduction
2.
Quick Sort
2.1.
Algorithm of Quick Sort
2.2.
Steps to sort an array using the quick sort algorithm
3.
Merge sort
3.1.
Steps to sort an array using the Merge sort algorithm
3.1.1.
Here's a step-by-step breakdown of the merging process
4.
Quick Sort vs. Merge Sort
5.
Frequently Asked Questions
5.1.
What is the main difference between quick sort and merge sort?
5.2.
Which algorithm is more efficient regarding space complexity?
5.3.
Is merge sort always preferred over quick sort?
6.
Conclusion
Last Updated: Oct 21, 2024
Easy

Quick Sort vs Merge Sort

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Sorting algorithms play a crucial role in computer science, as these help us to arrange data in a specific order for efficient searching, analysis, & processing. Among the various sorting algorithms, quick sort & merge sort are very popular among programmers as two popular & efficient methods. The quick sort is known for its speed & efficiency, while the merge sort is recognized for its stability & consistent performance. Both algorithms have unique approaches to sorting data, but understanding their differences is crucial for selecting the appropriate algorithm per the code's demand. 

Quick Sort vs Merge Sort

In this article, we will discuss the concepts of quick sort & merge sort, understand their algorithms, provide step-by-step explanations, & compare their characteristics.

Quick Sort

Quick sort is a powerful divide-and-conquer algorithm that efficiently sorts an array by selecting a pivot element 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 until the entire array is sorted.

The main idea behind quick sort is to divide the problem into smaller subproblems, solve them recursively, and then combine the solutions to solve the original problem. By selecting a pivot element and partitioning the array around it, quick sort ensures that the pivot element is in its final sorted position, and all elements to its left are smaller, while all elements to its right are larger.

One advantage of quick sort is its efficiency, especially for large arrays. On average, quick sort has a time complexity of O(n log n), which makes it one of the fastest sorting algorithms. 

Algorithm of Quick Sort

The quick sort algorithm follows these steps:

1. Choose a pivot element from the array (usually the first, last, or middle element).

2. Partition the array into two sub-arrays: elements less than the pivot & elements greater than the pivot.

3. Recursively apply steps 1 & 2 to the sub-arrays until the sub-arrays are empty or contain only one element.

4. Combine the sorted sub-arrays to obtain the final sorted array.

Note: The main idea of the quick sort algorithm is the partitioning step, which ensures that the pivot element is in its final sorted position & all elements to its left are smaller, while all elements to its right are larger.

Steps to sort an array using the quick sort algorithm

1. Select a pivot element from the array (e.g., the last element).
 

2. Initialize two pointers, left and right, pointing to the start and end of the array, respectively.
 

3. Move the left pointer forward until an element greater than the pivot is found.
 

4. Move the right pointer backward until an element smaller than the pivot is found.
 

5. Swap the elements at the left & right pointers if the left pointer is less than or equal to the right pointer.
 

6. Repeat steps 3-5 until the left pointer is greater than the right pointer.
 

7. Swap the pivot element with the element at the right pointer.
 

8. Recursively apply steps 1-7 to the sub-array to the left of the right pointer & the sub-array to the right of the right pointer.
 

9. Repeat until all sub-arrays are sorted.
 

For example : 

def quicksort(arr, low, high):
    if low < high:
        pivot_index = partition(arr, low, high)
        quicksort(arr, low, pivot_index - 1)
        quicksort(arr, pivot_index + 1, high)

def partition(arr, low, high):
    pivot = arr[high]
    i = low - 1
    for j in range(low, high):
        if arr[j] <= pivot:
            i += 1
            arr[i], arr[j] = arr[j], arr[i]
    arr[i + 1], arr[high] = arr[high], arr[i + 1]
    return i + 1


arr = [64, 34, 25, 12, 22, 11, 90]
quicksort(arr, 0, len(arr) - 1)
print(arr)
You can also try this code with Online Python Compiler
Run Code


Output:

[11, 12, 22, 25, 34, 64, 90]


The `quicksort` function is called with the array, the low index (initially 0), and the high index (initially the last index of the array). The `partition` function selects the last element as the pivot and partitions the array around it. The algorithm recursively sorts the sub-arrays until the entire array is sorted.

Merge sort

Merge sort is another divide-and-conquer algorithm that divides the array into two halves, recursively sorts each half, and then merges the sorted halves back together to obtain the final sorted array. The merging process combines two sorted sub-arrays into a single sorted sub-array.

The main idea behind merge sort is to break down the problem into smaller subproblems, solve them recursively, and then combine the solutions to solve the original problem. By repeatedly dividing the array in half, merge sort ensures that the subarrays become small enough to be easily sorted.

One of the advantages of merge sort is its stability, which means that the relative order of equal elements is preserved during the sorting process. This property becomes very useful when sorting objects with multiple attributes or when maintaining the original order of equal elements is important.

Merge sort has a guaranteed time complexity of O(n log n), which makes it efficient for sorting large arrays. 

Steps to sort an array using the Merge sort algorithm

1. Divide the unsorted array into two halves until each sub-array contains only one element or is empty.
 

2. Recursively sort the two sub-arrays using the merge sort algorithm.
 

3. Merge the sorted sub-arrays back together to obtain the final sorted array.

Here's a step-by-step breakdown of the merging process

1. Create a temporary array to store the merged elements.
 

2. Initialize two pointers, one for each sub-array, pointing to the first element of each sub-array.
 

3. Compare the elements at the pointers and copy the smaller element into the temporary array.
 

4. Move the pointer of the sub-array whose element was copied to the next position.
 

5. Repeat steps 3-4 until all elements from both sub-arrays are copied into the temporary array.
 

6. Copy the elements from the temporary array back into the original array.

For example : 

def mergesort(arr):
    if len(arr) <= 1:
        return arr
    
    mid = len(arr) // 2
    left = arr[:mid]
    right = arr[mid:]
    
    left = mergesort(left)
    right = mergesort(right)
    
    return merge(left, right)


def merge(left, right):
    merged = []
    left_index = right_index = 0
    
    while left_index < len(left) and right_index < len(right):
        if left[left_index] <= right[right_index]:
            merged.append(left[left_index])
            left_index += 1
        else:
            merged.append(right[right_index])
            right_index += 1
    
    merged.extend(left[left_index:])
    merged.extend(right[right_index:])
   
    return merged
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = mergesort(arr)
print(sorted_arr)
You can also try this code with Online Python Compiler
Run Code


Output:

[11, 12, 22, 25, 34, 64, 90]


The `mergesort` function recursively divides the array into two halves until each sub-array contains only one element or is empty. The `merge` function merges two sorted sub-arrays into a single sorted sub-array by comparing the elements and appending them to a temporary array. Finally, the sorted sub-arrays are merged back together to obtain the final sorted array.

Quick Sort vs. Merge Sort

ParametersQuick SortMerge Sort
Worst-case Time ComplexityO(n²) when the pivot selection is not optimal, leading to unbalanced partitions.O(n log n), guarantees this complexity even in the worst-case scenario.
Space ComplexityO(log n) additional space for recursive calls, as it is an in-place algorithm.O(n) additional space is required to store the auxiliary array for merging sub-arrays.
StabilityNot a stable sorting algorithm; equal elements may not retain their relative order.Stable sorting algorithm; preserves the relative order of equal elements.
Pivot SelectionRelies on the selection of a pivot element, and performance is highly impacted by the choice of pivot.Does not require a pivot element, making it simpler to implement and analyze.
Efficiency in PracticeOften faster than merge sort for smaller or partially sorted arrays.Provides consistent performance regardless of the initial order of elements, making it more predictable.
ParallelizationMore challenging to parallelize due to its partitioning nature and coordination between partitions.Easier to parallelize since merging sorted sub-arrays can be performed independently.
Preferred UsagePreferred when average-case performance is important, and the dataset fits well in memory.Preferred when worst-case guarantees are critical, stability is important, or when handling large datasets that don't fit in memory.

Frequently Asked Questions

What is the main difference between quick sort and merge sort?

The main difference lies in their partitioning and merging strategies. Quick sort partitions the array around a pivot element, while merge sort divides the array into two halves and merges them back together.

Which algorithm is more efficient regarding space complexity?

Quick sort is more space-efficient as it performs in-place sorting, requiring only O(log n) additional space for recursive calls. Merge sort, on the other hand, requires O(n) additional space to merge the sorted sub-arrays.

Is merge sort always preferred over quick sort?

Not necessarily. The choice depends on the specific requirements of the problem. Quick sort is often faster in practice and preferred when average-case performance is crucial, while merge sort is preferred when worst-case guarantees and stability are important.

Conclusion

In this article, we discussed the concepts, algorithms, and differences between quick sort and merge sort. Like every other concept, both algorithms have their strengths and weaknesses regarding time complexity, space complexity, stability, and efficiency. Quick sort is known for its practical efficiency and in-place sorting, while merge sort guarantees a consistent time complexity and maintains stability. The choice between the two depends on factors such as the size of the dataset, memory constraints, and the importance of worst-case performance. 

You can also check out our other blogs on Code360.

Live masterclass