Bubble Sort is a simple sorting technique in which a given set of elements provided in form of an array are sorted by simple conversion. It compares all the elements one by one and sort them accordingly.
If sorting is to be done in ascending order, then bubble sort will start by comparing the first element with the second element, if the first element is greater than the second element, it will swap them, and then compare it with the second and the third element, and so on. With every complete iteration the largest element in the given array, is placed at the last place or the highest index
Flowchart for Bubble Sort
Algorithm for Bubble Sort
Step 1: Start
Step 2: Read the array of given items from the user.
Step 3: Take the first element(index = 0), compare the current element with the next element.
Step 4: If the current element is greater than the next element, swap them.
Step 5: Else,
If the current element is less than the next element, then move to the next element.
Step 6: Repeat Step 3 to Step 5 until all elements are sorted.
Step 7: Stop
In the above algorithm,
- We first read the array from the user.
- We start by comparing the first element of the array with the second element, and in case if the first element is greater than the second element, we will swap both the elements, and then move on to compare the second and the third element, and continue till the end so on.
- If the first element is lesser than the second element then we move to the second and compare it with the third element and move so on.
- In case the is greater we follow the step 4 and if it'sless we follow step 5. Both of the are discussed above.
- We follow the same process until the given array is sorted.
Bubble Sort Algorithm Implementation in: