Assignment 3
Assignment 3
Question 2:
Code the following algorithms and simulate (dry-run) these by taking an unsorted
array with 05 elements:
Let's take the unsorted array: [5, 3, 8, 4, 2]
1. Insertion Sort
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int arr[] = {5, 3, 8, 4, 2};
int n = sizeof(arr)/sizeof(arr[0]);
insertionSort(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Let's simulate the dry run of the Insertion Sort algorithm for the given array `[5, 3, 8, 4, 2]`.
Initial Array:
[5, 3, 8, 4, 2]
Iteration 1:
-i=1
- key = arr[1] = 3
-j=i-1=0
- Compare key (3) with arr[j] (5):
- Since 3 < 5, move 5 to the right: arr[j + 1] = arr[j]
- Decrement j: j = -1
- Place key in the correct position: arr[j + 1] = 3
Output:
23458
2. Selection Sort
#include <iostream>
using namespace std;
Iteration 1:
Step 2: Find the minimum element in the unsorted portion of the array
- j = 1: Compare arr[j] = 3 with arr[min_idx] = 5
- 3 < 5, so update min_idx = j = 1
- j = 2: Compare arr[j] = 8 with arr[min_idx] = 3
- 8 > 3, so min_idx remains 1
- j = 3: Compare arr[j] = 4 with arr[min_idx] = 3
- 4 > 3, so min_idx remains 1
- j = 4: Compare arr[j] = 2 with arr[min_idx] = 3
- 2 < 3, so update min_idx = j = 4
Step 3: Swap the found minimum element with the first element**
- Swap arr[min_idx] = arr[4] = 2 with arr[i] = arr[0] = 5
- After swapping: arr[0] = 2, arr[4] = 5
[2, 3, 8, 4, 5]
Output:
23458
3. Merge Sort
#include <iostream>
using namespace std;
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
4. Quick Sort
#include <iostream>
using namespace std;
int main() {
int arr[] = {5, 3, 8, 4, 2};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Output:
23458