Question 2: [3 Marks]
Bubble sort is a simple sorting algorithm used to sort arrays. The Bubble sort algorithm compares each pair of elements in an array and swaps them if they are out of order until the entire array is sorted. Below we have a simple program for bubble sort.
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp, flag = 0;
for(i = 0; i < n; i++) {
for(j = 0; j < n-i-1; j++) {
// introducing flag to monitor swapping
if(arr[j] > arr[j+1]) {
// swap the elements
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
// if swapping happens, update flag to 1
flag = 1;
}
}
// if value of flag is zero after all the iterations of inner loop, then break out
if(flag == 0) {
break;
}
}
}
Apply the bubble sort algorithm to this array and give the number of comparisons Tj at each pass:
Pass 1:
A[0]
A[1]
A[2]
A[3]
Pass 2:
A[0]
A[1]
A[2]
Pass 3:
A[0]
A[1]
Pass 4:
A[0]
Based on the number of comparisons, give the complexity of the bubble sort algorithm at the worst case and the best case.
A[0]