Mark As Completed Discussion

Bubble Sort:

Bubble sort, also categorized as a “comparison-based” sorting algorithm, is a simple sorting algorithm that repeatedly goes through the collection, compares adjacent elements, and swaps them if they are not in sorted order. This is the simplest algorithm and inefficient at the same time. Yet, it is very important to learn about it as it represents the basic foundations of sorting. To perform sorting by this algorithm, the adjacent elements in the collection are compared and the positions are swapped if the first element is greater than the second one. In this way, the largest valued element "bubbles" to the top. Usually, after each loop, the elements furthest to the right are in sorted order. The process is continued until all the elements are in sorted order.

The working of bubble sort algorithm is simulated in below mentioned figure:

Bubble Sort

Here's the pseudocode:

SNIPPET
1procedure bubbleSort( arr[]: collection of elements, N: size of collection)
2   for i = 0 to N - 1 do:
3      swapped = false	
4      for j = 0 to N - i - 2 do:
5         if arr[j] > arr[j+1] then
6            swap(arr[j], arr[j+1])		
7            swapped = true
8         end if
9      end for
10      if(not swapped) then
11         break
12      end if
13   end for
14end

Time Complexity: O(N2)

Space Complexity: O(1)

Best Suited Scenario:

Bubble sort algorithm is best suited with most of the data structures and the given collection is in completely unsorted order. This algorithm is not feasible for very large number of data set and this is likely due to its time complexity.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment