Bubble sort in python

Sample code for Bubble sort in Python
#!/bin/python
import sys
print "Enter number of numbers"
n = int(raw_input().strip())
print "Enter numbers separated by space"
a = map(int,raw_input().strip().split(' '))
i = n
numberOfSwaps = 0
for i in xrange(n, 0, -1):
    for j in range(0,i-1):
        #print a[j]
        if a[j]>a[j+1]:
            temp = a[j] 
            a[j] = a[j+1]
            a[j+1] = temp
            numberOfSwaps =numberOfSwaps+1 ;
    i = i-1    
print "Sorted array :"
print a
Sample output(In Python 2.7):-
>>>
Enter number of numbers
5
Enter numbers separated by space
12 3 56 78 2
[2, 3, 12, 56, 78]

Explanation:-
raw_input()- Reads input from console. 
map(int,raw_input().strip().split(' '))- Read input from console and convert it into list
In python3 input() is used instead of raw_iput() to read input from console.

1 Comments

Previous Post Next Post