Experiment No.
1
Name of Experiment: MergeSort and QuickSort
Aim: Implement Merge sort and Quicksort for the given list of integer values and find space and
time complexity
Software Required: C/C++, Java Compiler
Pre-Requisites: C Programming Concepts, Data Structures
Theory:
Quicksort is a divide-and-conquer sorting algorithm. It works by selecting a pivot element from
the array and partitioning the other elements into two sub-arrays:
● Elements less than the pivot go to the left sub-array.
● Elements greater than the pivot go to the right sub-array.
The process is then recursively applied to the left and right sub-arrays. This results in the array
being sorted.
Key Features:
● Time Complexity (Average case): O(n log n)
● Time Complexity (Worst case): O(n²) (when the smallest or largest element is always
chosen as pivot)
● Space Complexity: O(log n) (for recursive calls)
● It is in-place (does not require extra memory for array storage).
● It is not stable (relative order of equal elements may change).
Algorithm: QUICKSORT
QUICKSORT(arr, low, high):
if low < high:
pivotIndex = PARTITION(arr, low, high)
QUICKSORT(arr, low, pivotIndex - 1)
QUICKSORT(arr, pivotIndex + 1, high)
PARTITION(arr, low, high):
pivot = arr[high] // Choose last element as pivot
i = low - 1 // Index of smaller element
for j = low to high - 1:
if arr[j] <= pivot:
i = i + 1
swap arr[i] and arr[j]
swap arr[i + 1] and arr[high]
return i + 1
Merge Sort is a divide-and-conquer sorting algorithm. It divides the input array into two
halves, recursively sorts them, and finally merges the two sorted halves into a single sorted
array.
Key Characteristics:
● It is a stable sorting algorithm (preserves the relative order of equal elements).
● Time Complexity (Best, Average, Worst): O(n log n)
● Space Complexity: O(n) (extra space is used for merging)
● Useful for linked lists and external sorting (sorting large data on disk).
● It is NOT in-place (requires extra memory for array storage).
Algorithm: MERGESORT
MERGESORT(arr, left, right):
if left < right:
mid = (left + right) / 2
MERGESORT(arr, left, mid)
MERGESORT(arr, mid + 1, right)
MERGE(arr, left, mid, right)
MERGE(arr, left, mid, right):
n1 = mid - left + 1
n2 = right - mid
create arrays L[1..n1] and R[1..n2]
copy arr[left..mid] into L
copy arr[mid+1..right] into R
i = 0, j = 0, k = left
while i < n1 and j < n2:
if L[i] <= R[j]:
arr[k] = L[i]
i = i + 1
else:
arr[k] = R[j]
j = j + 1
k = k + 1
// Copy any remaining elements
while i < n1:
arr[k] = L[i]
i = i + 1
k = k + 1
while j < n2:
arr[k] = R[j]
j = j + 1
k = k + 1
Conclusion:
Quicksort is a fast, in-place sorting algorithm using the divide-and-conquer approach, but its
performance depends on good pivot selection. Merge Sort, while requiring extra space, offers
consistent O(n log n) performance and is preferred when stability and predictable results are
important, especially for large datasets.