Top MCQs on BubbleSort Algorithm with Answers
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) โ> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) โ> ( 1 4 5 2 8 ), Swap since 5 > 4 … More on Bubble Sort
Question 1 |
What is the best time complexity of bubble sort?
N^2 | |
NlogN | |
N | |
N(logN)^2 |
Discuss it
Question 1 Explanation:
The bubble sort is at its best if the input data is sorted. i.e. If the input data is sorted in the same order as expected output. This can be achieved by using one boolean variable. The boolean variable is used to check whether the values are swapped at least once in the inner loop.
Consider the following code snippet:
int main()
{
int arr[] = {10, 20, 30, 40, 50}, i, j, isSwapped;
int n = sizeof(arr) / sizeof(*arr);
isSwapped = 1;
for(i = 0; i < n - 1 && isSwapped; ++i)
{
isSwapped = 0;
for(j = 0; j < n - i - 1; ++j)
if (arr[j] > arr[j + 1])
{
swap(&arr[j], &arr[j + 1]);
isSwapped = 1;
}
}
for(i = 0; i < n; ++i)
printf("%d ", arr[i]);
return 0;
}
[/sourcecode]
Please observe that in the above code, the outer loop runs only once.
Question 2 |
Assume that we use Bubble Sort to sort n distinct elements in ascending order. When does the best case of Bubble Sort occur?
When elements are sorted in ascending order | |
When elements are sorted in descending order | |
When elements are not sorted by any order | |
There is no best case for Bubble Sort. It always takes O(n*n) time |
Discuss it
Question 3 |
The number of swappings needed to sort the numbers 8, 22, 7, 9, 31, 5, 13 in ascending order, using bubble sort is
11 | |
12 | |
13 | |
10 |
Discuss it
Question 3 Explanation:
1 : 8, 7, 9, 22, 5, 13, 31 = 4 swaps
2 : 7, 8, 9, 5, 13, 22, 31 = 3 swaps
3 : 7, 8, 5, 9, 13, 22, 31 = 1 swap
4 : 7, 5, 8, 9, 13, 22, 31 = 1 swap
5 : 5, 7, 8, 9, 13, 22, 31 = 1 swap
Total 10 swaps are required to sort the array.
There are 3 questions to complete.
Coding practice for sorting.