dsa
dsa
Definition:
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an
unsorted list into its correct position in a sorted portion of the list. It is a stable sorting
algorithm, meaning that elements with equal values maintain their relative order in the sorted
output.
Logic:
Code:
• Best case: O(n) , If the list is already sorted, where n is the number of
elements in the list.
• Average case: O(n 2 ) , If the list is randomly ordered
• Worst case: O(n 2 ) , If the list is in reverse order
Quick Sort:
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a
pivot and partitions the given array around the picked pivot by placing the pivot in its correct
position in the sorted array.
• Best Case : Ω (N log (N))
The best-case scenario for quicksort occur when the pivot chosen at the each step divides
the array into roughly equal halves.
In this case, the algorithm will make balanced partitions, leading to efficient Sorting.
• Average Case: θ ( N log (N))
Quicksort’s average-case performance is usually very good in practice, making it one of
the fastest sorting Algorithm.
• Worst Case: O(N ^ 2)
The worst-case Scenario for Quicksort occur when the pivot at each step consistently
results in highly unbalanced partitions. When the array is already sorted and the pivot is
always chosen as the smallest or largest element. To mitigate the worst-case Scenario,
various techniques are used such as choosing a good pivot (e.g., median of three) and
using Randomized algorithm (Randomized Quicksort ) to shuffle the element before
sorting.
• Auxiliary Space: O(1), if we don’t consider the recursive stack space. If we consider the
recursive stack space then, in the worst case quicksort could make O ( N ).
Bubble Sort:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in the wrong order. This algorithm is not suitable for large data sets as its
average and worst-case time complexity are quite high.
Time Complexity: O(n2)
Auxiliary Space: O(1)
Advantages of Bubble Sort:
• Bubble sort is easy to understand and implement.
• It does not require any additional memory space.
• It is a stable sorting algorithm, meaning that elements with the same key value maintain
their relative order in the sorted output.
Merge Sort
Merge sort is a sorting algorithm that follows the divide-and-conquer approach. It
works by recursively dividing the input array into smaller subarrays and sorting those
subarrays then merging them back together to obtain the sorted array.
omplexity Analysis of Merge Sort:
• Time Complexity:
o Best Case: O(n log n), When the array is already sorted or nearly sorted.
o Average Case: O(n log n), When the array is randomly ordered.
o Worst Case: O(n log n), When the array is sorted in reverse order.