Professional Documents
Culture Documents
Bubble Sorting
Bubble Sorting
Example:
We have array A .Sort the following array in Ascending order.
5 2 1 4 6 3
0 1 2 3 4 5
Expected Result:
1 2 3 4 5 6
0 1 2 3 4 5
Strategy:
There are many strategies for solving this, but first we will use bubble sorting .
Sorting:
First pass:
Step 1:
5 2 1 4 6 3
0 1 2 3 4 5 (index number)
2 5 1 4 6 3
0 1 2 3 4 5
2nd step:
2 5 1 4 6 3
2 1 5 4 6 3
0 1 2 3 4 5
3rd step:
2 1 5 4 6 3
0 1 2 3 4 5
2 1 4 5 6 3
0 1 2 3 4 5
4th step:
2 1 4 5 6 3
0 1 2 3 4 5
2 1 4 5 6 3
0 1 2 3 4 5
5th step:
2 1 4 5 6 3
0 1 2 3 4 5
Now bubble will shift to 6 compare 4 index with 5 . swap since 6 >3
2 1 4 5 3 6
0 1 2 3 4 5
Pass 2:
Now again start from index 0 and compared them all.
Step 1:
2 1 4 5 3 6
0 1 2 3 4 5
1 2 4 5 3 6
0 1 2 3 4 5
Step 2:
1 2 4 5 3 6
0 1 2 3 4 5
1 2 4 5 3 6
0 1 2 3 4 5
Step 3 :
1 2 4 5 3 6
0 1 2 3 4 5
Now bubble will shift to index 3 . we will compare index 3 with 4 . don’t swap because 4<5.
1 2 4 5 3 6
0 1 2 3 4 5
Step 4 :
1 2 4 5 3 6
0 1 2 3 4 5
Now bubble will shift to index 4 . we will compare index 4 with 5 . swap since 5 > 3.
1 2 4 3 5 6
0 1 2 3 4 5
Pass 3 :
Step 1 :
1 2 4 3 5 6
1 2 4 3 5 6
0 1 2 3 4 5
Step 2:
1 2 4 3 5 6
0 1 2 3 4 5
0 1 2 3 4 5
Now the array is already sorted but our algorithm does not know the algorithm need one whole pass
without any swap to know it is sorted.
Pass 3:
Step 1:
1 2 3 4 5 6
1 2 3 4 5 6
Step 2 :
1 2 3 4 5 6
1 2 3 4 5 6
Step 3:
1 2 3 4 5 6
1 2 3 4 5 6
Step 4 :
1 2 3 4 5 6
1 2 3 4 5 6
Step 5 :
1 2 3 4 5 6
1 2 3 4 5 6
3. Then start search of another smaller element without looking into index 0.
Example:
We have an array A :
15 28 6 19 9
0 1 2 3 4 (index number)
Expected result:
6 9 15 19 28
Sorting:
Step 1:
15 28 6 19 9
0 1 2 3 4
we will start our search from index 0 and find the smallest element. Swap element of index 2 with index
0.
6 28 9 19 15
0 1 2 3 4
Step 2:
6 28 9 19 15
0 1 2 3 4
Now we will again start searching for smallest number but this time we will start search from index 1.
6 9 28 19 15
0 1 2 3 4
Step 3:
6 9 28 19 15
0 1 2 3 4
Now start the search from index 2 and find smallest element.
6 9 15 19 28
0 1 2 3 4