Here you’ll find out about Python bubble type.
In Bubble type, all we’ve got to try and do is decide the primary 2 components of the array and compare them if the first one is larger than the second then swap them. After it, decide the next 2 components and compare them and then on.
After travelling the array once, the best variety is placed on the last index.
To type entire array we’ve got to travel the array (n-1) times wherever n is that the length of the array.
Bubble type is the simplest algorithm that works by repeatedly swapping the adjacent components if they’re in the wrong order.
Algorithm:
First Pass:
( five one four a pair of eight ) –> ( 1 5 4 2 8 ), Here, rule compares the primary 2 components, and swaps since five > one.
( one five four a pair of eight ) –> ( 1 4 5 2 8 ), Swap since five > four
( one four five a pair of eight ) –> ( 1 4 2 5 8 ), Swap since five > a pair of
( one four a pair of five eight ) –> ( 1 4 2 5 8 ), Now, since these components are already so as (8 > 5), the rule doesn’t swap them.
Second Pass:
( one four a pair of five-eight ) –> ( 1 4 2 5 8 )
( one four a pair of five-eight ) –> ( 1 2 4 5 8 ), Swap since four > a pair of
( one a pair of four five-eight ) –> ( 1 2 4 5 8 )
( one a pair of four five-eight ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, however our rule doesn’t understand if it’s completed. The rule wants one whole pass with none swap to grasp it’s sorted.
Third Pass:
( one a pair of four five-eight ) –> ( 1 2 4 5 8 )
( one a pair of four five-eight ) –> ( 1 2 4 5 8 )
( one a pair of four five-eight ) –> ( 1 2 4 5 8 )
( one a pair of four five-eight ) –> ( 1 2 4 5 8 )
Program for Bubble Sort in Python
Arr = [21,14,18,25,9]
n = len(Arr) #length
Pass = 1
while(Pass<=n-1):
index = 0
while(index<=n-Pass-1):
if Arr[index]>Arr[index+1]:
Arr[index],Arr[index+1] = Arr[index+1],Arr[index] #swapping
index = index+1
Pass =Pass + 1
for item in Arr:
print item,
Output
9 14 18 21 25
comment Down if you any doughts about this program.