Bubble Sort
Bubble sort is a simple sorting algorithm that works by repeatedly comparing adjacent elements in an array and swapping them if they are in the wrong order.
The algorithm starts at the beginning of the array and compares the first two elements. If the first element is greater than the second element, the two elements are swapped. The algorithm then moves on to the next two elements and repeats the process. This continues until the end of the array is reached(j < n - i
).
At every ith round, we deliver its ith largest element at the right place.
Use Case
Use Case
In general, bubble sort should only be used when speed is not a major concern or when the array is already mostly sorted.
Question statement:
https://www.codingninjas.com/studio/problems/bubble-sort_980524
Notes:
https://drive.google.com/file/d/1DScaSvG0TzAy2b9MF9CcEtzoOxvai3MY/view
Solved by Recursion
Code Explanation:
The
for
loop iterates from 1 ton-1 (1<n)
, wheren
is the number of elements in the array.The
bool
variableisSorted
is initialized totrue
. This variable will be used to track whether the array is already sorted.The
for
loop iterates from 0 ton-i-1 (O<n-i)
, wherei
is the current iteration of the outer loop.The
if
statement checks if the current element is greater than the next element. If it is, the two elements are swapped.The
isSorted
variable is set tofalse
if the array is not sorted. This will cause the outer loop to continue iterating.The outer
if
statement checks if the array is sorted. If it is, the algorithm terminates.
Best Case:
If any case comes where no. of swaps doesn't exit so, move out by breaking no need to do anything. Its Already shorted O(n).
The bubble sort algorithm is a very simple algorithm to understand and implement. However, it is also a very inefficient algorithm, with a worst-case time complexity of O(n^2). This means that the time it takes to sort an array using bubble sort grows quadratically with the size of the array. For this reason, bubble sort is not a good choice for sorting large arrays.
However, bubble sort can be a good choice for sorting small arrays or for sorting arrays that are already mostly sorted. In these cases, the inefficiency of bubble sort may not be a major concern.
Last updated
Was this helpful?