Dsa 2nd Assignment
Dsa 2nd Assignment
1. Merge Sort
2. Quick Sort
1. Merge Sort:
Merge Sort is a divide-and-conquer algorithm that recursively splits the array into halves, sorts each half,
and then merges the sorted halves back together.
Steps:
1. Divide: Recursively divide the array into two halves until each subarray contains a single
element.
Algorithm:
o Merge the two sorted halves to produce the final sorted array.
Space Complexity: O(n) due to the additional space required for merging.
1. Split: [38, 27, 43, 3, 9, 82, 10] → [38, 27, 43] and [3, 9, 82, 10]
2. Further split: [38, 27, 43] → [38] and [27, 43]; [27, 43] → [27] and [43]
3. Sort and merge: [27, 43] → [27, 43]; merge with [38] → [27, 38, 43]
4. Similarly, process the second half [3, 9, 82, 10] → [3, 9, 10, 82]
5. Merge the two halves: [27, 38, 43] and [3, 9, 10, 82] → [3, 9, 10, 27, 38, 43, 82]
Explanation of Quick Sort:
2. Quick Sort:
Quick Sort is another divide-and-conquer algorithm but works by selecting a pivot element and
partitioning the array such that elements smaller than the pivot are on one side, and elements larger are
on the other. It then recursively sorts the subarrays.
Steps:
1. Partition: Choose a pivot element (often the first, last, or middle element).
2. Divide: Rearrange elements so that all elements smaller than the pivot are to the left,
and all elements greater are to the right.
3. Recursion: Recursively apply the same process to the left and right subarrays.
Algorithm:
o Select a pivot.
Time Complexity:
o Worst case: O(n²) (when the pivot is consistently the smallest or largest element)
Example: For an array [10, 80, 30, 90, 40, 50, 70]:
3. Apply Quick Sort to [10, 40, 30, 50] and [80, 90].