Assignment 2 PRG181
Assignment 2 PRG181
Nigel Katsande
603150
Tetelo Phahladira
601950
Course PRG 181
Assignment 1
Due Date 12 March 2024
Question 2
Merge Sort algorithm with the given 1D array [34, 22, 5, 15, 27, 55, 8, 29, 3, 44, 6, 4]:
1. Divide:
The array will be divided into two halves. The midpoint is calculated (in this case, it is 6) and the
array is divided into:[34, 22, 5, 15, 27, 55] and [8, 29, 3, 44, 6, 4].
2. Recursively Divide: Recursively divide each half of the array until each sub-array has only
one element. The sub arrays will respectively be [34,22], [5,15], [27,55] and [8,29], [3,44], [6,4].
They will further be divided until they are individual elements.
3. Merge:
Now we will begin merging the sub arrays back together in sorted order.
Firstly we will merge elements [34] and [22]. Since 34 is greater than 22, the sorted order will be
[22, 34].
For element 5 and 15, the sorted order will be [5,15].
For element 27 and 55 , the sorted order will be [27,55].
For element 8 and 29, the sorted order will be [8,29].
For element 3 and 44 , the sorted order will be [3,44].
For element 6 and 4, the sorted order will be [4,6].
4. Merge the two sub arrays [22, 34, 5, 15, 27, 55] and [8, 29, 3, 44, 6, 4] from the other smaller
sorted sub arrays together to get the final sorted array. These two sub arrays will become [5, 15,
22, 27, 34, 55] and [3, 4, 6, 8, 29, 44] when sorted.
So, the final sorted array using Merge Sort for the given 1D array will be = [5, 8, 15, 22, 27, 29,
34, 44, 55]
Quick Sort algorithm:
1.Pivot: Select a pivot element from the array. The most common approach is to choose the last
element of the array as the pivot. In this case, let’s choose 4 as the pivot.
34 22 5
2. **Partitioning**:
- Partition the array around the pivot. All elements smaller than the pivot will be placed to the
left, and all elements greater than the pivot will be placed to the right.
- The partitioning step rearranges the elements so that the pivot is in its final sorted position.
After partitioning, the array may look like this:
`[22, 5, 15, 27, 8, 29, 3, 6, 4, 34, 44, 55]`
- At this point, 4 (pivot) is in its correct position.
3. **Recursive Step**:
- Now, the array is divided into two sub-arrays based on the pivot (4).
- Left sub-array: `[22, 5, 15, 27, 8, 29, 3, 6]`
- Right sub-array: `[34, 44, 55]`
In Quick Sort:
- The key to the algorithm is selecting the pivot. It can significantly affect the performance of the
algorithm.
- The partitioning step partitions the elements such that the elements smaller than the pivot are on
the left, and elements greater than the pivot are on the right.
- Recursively apply the algorithm to the sub-arrays until the whole array becomes sorted.
By following these steps, we can effectively execute the Quick Sort algorithm for the given 1D
array.
Bibliography