Assignment 3
Assignment 3
• Merge Sort
• Merge Sort divides the array into two halves, recursively sorts each half, and then
merges the sorted halves to produce the final sorted array.
• The merging process is where the "conquer" part occurs, as it combines two sorted
subarrays into a single sorted array.
• Time Complexity: O(nlogn)O(n \log n)O(nlogn) for all cases (best, average, and
worst).
• Quick Sort
• Quick Sort selects a "pivot" element, partitions the array so that elements less than the
pivot are on the left and elements greater than the pivot are on the right, and then
recursively sorts the partitions.
• The divide step occurs at each recursive call, where the array is divided into subarrays
around the pivot.
• Time Complexity: O(nlogn)O(n \log n)O(nlogn) on average, but
O(n2)O(n^2)O(n2) in the worst case (typically mitigated by using randomized or
median pivot selection).
Q2. Apply quick sort algorithm to sort the following data. Justify the steps. 42,
29, 74, 11, 65, 58 .
#include <stdio.h>
int main() {
int arr[] = {42, 29, 74, 11, 65, 58};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
1. Choose a Pivot: Select an element from the array to be the pivot (commonly the last
element).
2. Partition the Array: Rearrange the elements in the array so that all elements less
than the pivot are to its left and all elements greater are to its right.
3. Recursively Apply Quick Sort: Recursively apply the above steps to the sub-arrays
formed by dividing at the pivot.
4. The process continues until each sub-array has only one element or is empty, resulting
in a sorted array.
1. Divide: Divide the unsorted list into nnn sublists, each containing one element.
2. Merge: Repeatedly merge sublists to produce new sorted sublists until there is only
one sublist remaining, which is the sorted list.
3. During the merge process, compare elements from two sublists and combine them
into a new sorted list.
Binary Search works by repeatedly dividing the search interval in half. If the value of the
search key is less than the item in the middle of the array, the search continues in the left half,
or if the value is greater, it continues in the right half.