Sorting
Merge Sort
• Merge Sort is a Divide and Conquer algorithm. It divides the
input array into two halves, calls itself for the two halves, and
then merges the two sorted halves.
• The merge() function is used for merging two halves. The
merge(arr, l, m, r) is a key process that assumes that arr[l..m]
and arr[m+1..r] are sorted and merges the two sorted sub-
arrays into one.
• array is recursively divided in two halves till the size becomes 1. Once the
size becomes 1, the merge processes come into action and start merging
arrays back till the complete array is merged.
Bubble sort
• Bubble sort, sometimes referred to as sinking
sort, is a simple sorting algorithm that repeatedly
steps through the list, compares adjacent
elements and swaps them if they are in the
wrong order.
• The pass through the list is repeated until the list
is sorted. The algorithm, which is a
comparison sort, is named for the way smaller or
larger elements "bubble" to the top of the list.
• Worst and Average Case Time
Complexity: O(n*n). Worst case occurs when
array is reverse sorted.
Best Case Time Complexity: O(n). Best case
occurs when array is already sorted.
Summary
Sort Best case Average case Worst case
Bubble Sort n n2 n2
Merge Sort nlogn nlogn nlogn
Selection sort n n2 n2
Insertion Sort n n2 n2