Bubble sort
Procedure:
Bubble sort algorithm
starts by comparing the first two elements of an array and swapping if
necessary.
Step 1:
Compare first and second data items. If the first data item is greater than the
second data item, then interchange first and second data items. If the second
data item is greater than the third data item, then interchange second and
third data items. This process is repeated till the last data item is reached.
Step 2:
When the last data item is reached, it is said to be one pass. At the end of
the first pass, the largest element is bubble out and occupies the last
position in the array.
Step 3: Step 1 and 2 are repeated for the data items
between 1 to n-1. At the end of the second pass, the next highest element is
bubble out and occupies n-1th position in the array.
Step 4:
These steps are repeated for n-1 process
Step 5:
At the end of the n-1th pass, all
elements of the array are available in sorted order.
Algorithm:
Repeat
for i<-- 1 to n-1 DO STEP BY 1
Repeat
j<--1 to n-i DO STEP BY 1
If a[j] > a[j+1] then
temp <-- a[j]
a[j] <-- a[j+1]
a[j+1] <-- temp
End If
End Repeat
End
Repeat
Example:
Before sorting the given array is a[5]={-2,45,0,11,-9}
0 comments:
Post a Comment