Data Sturcture and Algorithm Week 10
Data Sturcture and Algorithm Week 10
Semester – II Semester
EA2331201010152
1. Illustrate the insertion sort algorithm for the following array. 3 2 4 1 8 7 5
Insertion sort iterates through the array, gradually building a sorted sub-array at the
beginning. For each element, it compares it with the elements in the sorted sub-array and
inserts it in its correct position.
Array: 3 2 4 1 8 7 5
Steps:
Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares
adjacent elements, and swaps them if they are in the wrong order. The pass through the list is
repeated until no swaps are needed, which indicates that the list is sorted. In each pass, the
largest element "bubbles" up to its correct position at the end of the list.
Array: 5 1 4 2 8 7 3
EA2331201010152
Steps:
• Pass 1:
o Compare the first two elements (5 and 1). Since 5 is greater than 1, swap them.
o Continue comparing and swapping adjacent elements throughout the unsorted
portion of the list (marked with 'X' below). In each comparison, the larger
element is swapped to the right.
Array: 1 5 4 2 8 7 3 (X)
• Pass 2:
o Repeat the comparison and swapping process within the unsorted portion,
excluding the elements already fixed in pass 1. With each pass, the unsorted
portion shrinks as elements move to their correct positions.
Array: 1 4 5 2 8 7 3 (X)
• Pass 3:
o Comparisons and swaps continue within the shrinking unsorted portion. As
more elements reach their correct positions, the unsorted portion becomes
smaller.
Array: 1 2 4 5 8 7 3 (X)
• Pass 4:
o At this point, only one comparison is needed (between the second and third
elements from the end) as the largest element (8) has already bubbled up to the
end. If the elements are in the correct order (no swap required), this pass
indicates that the list is sorted.
Array: 1 2 3 4 5 7 8 (Sorted)
EA2331201010152