![]() |
VOOZH | about |
Bubble Sort is a comparison based simple sorting algorithm that works by comparing the adjacent elements and swapping them if the elements are not in the correct order. It is an in-place and stable sorting algorithm that can sort items in data structures such as arrays and linked lists.
1 3 5 6
Time Complexity: O(n2), where n is the number of items in the list.
Auxiliary Space: O(1)
Bubble-sort is an in-place and stable sorting algorithm (i.e. the relative order of the elements remains the same after sorting) that can sort items in data structures such as arrays and linked lists. It performs n-1 passes of the array/linked list and in each pass the largest unsorted element is moved to its correct position.
To modify the bubble sort algorithm for sorting in decreasing order we simply need to move the smallest unsorted element to the end by changing the condition for swapping (i.e. swap the elements if the (i+1)th element is greater than ith element).
The bubble sort algorithm may perform all (n-1) passes even if the array is already sorted. Using a swapped flag in the inner loop allows the algorithm to detect if any swaps occurred, stopping early if the array is sorted.
Note: Although this approach improves the performance of bubble sort in cases where the array gets sorted in earlier passes, it does not change its worst-case time complexity.
1 3 5 6
Time Complexity: O(n2)
Auxiliary Space: O(1)