Bubble Sort
- Shreyas Naphad
- May 3, 2024
- 1 min read
Updated: Jun 5, 2024
Sorting is one of the most important techniques in Computer Science and in this article, we will be learning one of the most common sorting techniques which is the Bubble Sort algorithm.
In simple words, Bubble sorting is like arranging books on a shelf by repeatedly swapping the adjacent books until all the books are in the right order. In Bubble sort, after every iteration, the n-ith position is sorted.
The Problem Statement is as follows:
Given an array of N integers, sort the elements of the array using the Bubble Sorting algorithm.
Example:
Input: N = 4, array[] = {5,1,0,2}
Output: 0,1,2,5
Bubble Sorting Algorithm:
Start from the beginning of the array.
Compare the first two elements. If the first one is greater than the second one, swap them as the order is wrong.
Move to the next pair of elements, and repeat the comparison and swapping process.
Continue this process by moving through the array one pair at a time, until you reach the end of the array.
After the first iteration is completed, the largest element will "bubble up" to the end.
Now repeat steps 1-5 for the remaining unsorted elements, such that the largest element of the unsorted array will go to its right position after every iteration
Continue these steps until the entire list is sorted.
Bubble Sort Code in C++
Time complexity: O(N^2)
Space Complexity: O(1)
Kommentare