Algorithm
- Compare each pair of adjacent elements from the beginning of an array and, if they are in reversed order, swap them.
- If at least one swap has been done, repeat step 1.
Example, sort (5, 1, 12, -5, 16) using bubble sort
Sorting Process :
5 1 12 -5 16 --> unsorted
5 1 12 -5 16 --> 5 > 1, swap
1 5 12 -5 16 --> 5 < 12, ok
1 5 12 -5 16 --> 12 > -5, swap
1 5 -5 12 16 --> 12 < 16, ok
1 5 -5 12 16 --> 1 < 5, ok
1 5 -5 12 16 --> 5 > -5, swap
1 -5 5 12 16 --> 5 < 12, ok
1 -5 5 12 16 --> 1 > -5, swap
-5 1 5 12 16 --> 1 < 5, ok
-5 1 5 12 16 --> -5 < 1, ok
-5 1 5 12 16 --> sorted
Tidak ada komentar:
Posting Komentar