Unit 12_13.1 Pr
Unit 12_13.1 Pr
Sorting
Steps:
3. Move the boundary of the sorted section one element to the right.
Time Complexity:
b. Bubble Sort
Bubble Sort repeatedly compares adjacent elements in the array and swaps them if
they are in the wrong order. Larger elements 'bubble up' to the end of the array in each
iteration.
Steps:
2. Pass through the array repeatedly, ignoring the last sorted elements in each
subsequent pass.
Time Complexity:
c. Shell Sort
Shell Sort is an optimization of insertion sort. It starts by sorting elements far apart
and progressively reduces the gap between elements to be compared. The final
iteration performs a standard insertion sort.
Steps:
Time Complexity:
2) How would you choose which sorting techniques are the most efficient for a set of data?
23
45
13
5
56
74
10
30
65
40
Passes:
1. Find the smallest element (5) and swap with the first element:
45
13
23
56
74
10
30
65
40
Comparisons: 9
Exchanges: 1
2. Find the next smallest (10) and swap with the second element:
10
13
23
56
74
45
30
65
40
Comparisons: 8
Exchanges: 1
10
13
23
30
40
45
56
65
74
Total Comparisons: 45
Total Exchanges: 9
4) Identify the comparisons and the exchanges made to sort the array found in problem 3
using the bubble sort technique.
Initial Array:
23
45
13
56
74
10
30
65
40
Passes:
1. Compare adjacent elements, swapping if needed. After the first pass, the largest
element (74) is at the end:
Array:
23
13
45
56
10
30
65
40
74
Comparisons: 9
Exchanges: 4
2. Repeat for the remaining unsorted portion, with fewer comparisons each time:
Final Array:
5
10
14
23
30
40
45
56
65
74
Total Comparisons: 45
Total Exchanges: 20
5) Identify the comparisons and the exchanges made to sort the array found in problem 3
using the shell sort technique.
Initial Array:
23
45
13
56
74
10
30
65
40
Steps:
1. Choose an initial gap (e.g., 5):
Compare elements 5 positions apart. Perform gapped insertion sort.
Array:
10
30
13
40
23
74
45
65
56
Comparisons: 5
Exchanges: 3
2. Reduce the gap to 2:
Perform gapped insertion sort for gap 2.
Array:
5
10
13
23
30
40
45
56
65
74
Comparisons: 9
Exchanges: 4
3. Reduce the gap to 1 (standard insertion sort):
Sort normally.
Array:
5
10
13
23
30
40
45
56
65
74
Comparisons: 10
Exchanges: 0
Total Comparisons: 24
Total Exchanges: 7