What is Bubble sort in Data Structure? | Data Structure Tutorial
Bubble sort in Data Structure
In this article, you will understand the bubble sort in the data structure in brief.
Bubble sort is a sorting program that compares two adjacent elements and swaps them until they are in the intended position.
Bubble sort algorithm steps
Steps to sort the elements in the ascending order
- First Iteration
- Take the first element, and compare the first and second elements.
- If the value of the first element is greater than the second element, they are swapped.
- Now, again check the second and third elements. Swap them if the value of the second element is greater than the third element.
- Do the same process until the last element.
- Other iteration
Do the same steps again and again until the elements of the complete array are sorted.
After each iteration takes place, the largest element will be placed at the end of the unsorted elements. Once the largest element is reached the last element, the sorted algorithm will take place on other unsorted elements. This will go in such a way until the array is not sorted.
Bubble sort Algorithm
bubble_sort(array) for i <- 1 to indexofLastElement-1 if leftElement > rightElement swap leftElement and rightElement end bubble_sort
The complexity of Bubble Sort
The best time complexity is O(n), the average time complexity is O(n2), and the worst case complexity is O(n2).
Space complexity is O(1).
Applications of Bubble sort
- It is used when the complexity does not matter.
- It is used when short and uncomplicated code is preferred.