Python Day 20: Sorting




Given an array, a, of size n distinct elements, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following 3 lines:



  1. n = int(input().strip())
  2. a = list(map(int, input().strip().split(' ')))
  3. numSwaps = 0
  4. for i in range(n):
  5. currentSwaps = 0
  6. for j in range(n-1):
  7. if a[j] > a[j+1]:
  8. tmp = a[j]
  9. a[j] = a[j+1]
  10. a[j+1] = tmp
  11. numSwaps += 1
  12. currentSwaps += 1
  13. if currentSwaps == 0:
  14. break
  15. print('Array is sorted in ' + str(numSwaps) + ' swaps.')
  16. print('First Element: ' + str(a[0]))
  17. print('Last Element: ' + str(a[n-1]))




codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube