Professional Documents
Culture Documents
Bubble Sort
Bubble Sort
STRUCTURES
MAHESH GOYANI
MAHATMA GANDHI INSTITUE OF TECHNICAL EDUCATION & RESEARCH CENTER
mgoyani@rediffmail.com
In pseudo code:
do
for each element e from first to penultimate unsorted
if e is out of order with the following element
swap the elements
while swap occurred in last pass
6 12 14
8 14
8 17 22
6 8 12 14 17 22
45312
45312
43512
45312
43512
43152
45312
43512
43152
45312
43512
43152
45312 34125
43512
43152
45312 34125
43512 31425
43152
45312 34125
43512 31425
43152 31245
45312 34125
43512 31425
43152 31245
43512 31425
43152 31245
43152 31245
43152 31245
43152 31245
7 2 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8
2 7 8 5 4 2 7 5 4 8 2 5 4 7 8 2 4 5 7 8
2 7 8 5 4 2 5 7 4 8 2 4 5 7 8 (done)
2 7 5 8 4 2 5 4 7 8
2 7 5 4 8
Each pass bubbles the highest remaining element to the top of the array; in
the worst case there could be n-1 passes, thus the outer loop would execute n-1
times;
for the first iteration of the outer loop, the inner loop executes n-1 times
for the second iteration of the outer loop, the inner loop executes n-2
times
etc
for the last iteration of the outer loop, the inner loop executes 1 time
thus the execution time is (n-1) + (n-2) + (n-3) + … + 3 + 2 + 1
the sum of this series is (n2 - n) / 2
bubble sort is O(n2 )