Optimized Bubble Sort
In the bubble sort algorithm, comparisons are made even when the array is already sorted. Because of that, the execution time increases.
To solve it, we can use an extra variable swapped. It is set to true if swapping requires; otherwise, it is set to false.
It will be helpful, as suppose after an iteration, if there is no swapping required, the value of variable swapped will be false. It means that the elements are already sorted, and no further iterations are required.
This method will reduce the execution time and also optimizes the bubble sort.
Algorithm
bubbleSort(array)
n = length(array)
repeat
swapped = false
for i = 1 to n - 1
if array[i - 1] > array[i], then
swap(array[i - 1], array[i])
swapped = true
end if
end for
n = n - 1
until not swapped
end bubbleSort