Search code examples
pythonbubble-sort

python bubble sort error


I tried to write a bubble sort program which doesn't work

n = raw_input("enter no of elements to be added in array")

print 'enter elements for an array to be sorted'
arr = []

for i in range(n):
    p=raw_input("enter next element of array\n")
    arr.append(p)
for j in range (len(arr)-1):
    for k in range(len(arr)-j-1):
        if(arr[k]>arr[k+1]):
           temp=arr[k]
           arr[k]=arr[k+1]
           arr[k+1]=temp

print("the sorted array is")
print arr

for example if i enter input no as "10,9,8,7,6,5,4,3,2,1" the sorted array comes out to be "1,10,2,3,4,5,6,7,8,9" for array "639,541,854,45,8" the answer is "854,45,639,45,541"


Solution

  • your program should be like

      n = input("enter no of elements to be added in array")
    
      print 'enter elements for an array to be sorted'
      arr = []
    
      for i in range(n):
          p=input("enter next element of array\n")
          arr.append(p)
      for j in range (len(arr)-1):
           for k in range(len(arr)-j-1):
               if(arr[k]>arr[k+1]):
                    temp=arr[k]
                    arr[k]=arr[k+1]
                    arr[k+1]=temp
    
      print("the sorted array is")
      print arr
    

    you should check how 'input' and 'raw_input' works

    at the following link

    What's the difference between raw_input() and input() in python3.x?