BubbleSort

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

1
Question 1
What is the best time complexity of bubble sort?
A
N^2
B
NlogN
C
N
D
N(logN)^2
Analysis of Algorithms    Sorting    BubbleSort    
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: 1 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?
A
When elements are sorted in ascending order
B
When elements are sorted in descending order
C
When elements are not sorted by any order
D
There is no best case for Bubble Sort. It always takes O(n*n) time
Sorting    BubbleSort    
Discuss it


There are 2 questions to complete.
1

 

Coding practice for sorting.

 

Company Wise Coding Practice    Topic Wise Coding Practice