m2skills

selection py

Apr 7th, 2017
836
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.82 KB | None | 0 0
  1. # program to implement selection sort
  2. def selectionSort(myList):
  3.     # loop i from 0 to n-1
  4.     for i in range(0,len(myList)):
  5.         # in each iteration we take i as index of the smallest element
  6.         minIndex = i
  7.         # loop j from i to n-1 (unsorted subarray from i to n-1)
  8.         # compare jth element to minIndex element
  9.         for j in range(i+1, len(myList)):
  10.             if myList[minIndex] > myList[j]:
  11.                 minIndex = j
  12.                
  13.         # swap the smallest element to the minIndex position
  14.         myList[i], myList[minIndex] = myList[minIndex], myList[i]
  15.         # remove the following comment to view the sorted subarray
  16.         # print(myList)
  17.        
  18.     return myList
  19.  
  20. # main function
  21. print("Enter the array to be sorted : ")
  22. myList1 = list(map(int, input().strip().split(",")))
  23.  
  24. selectionSort(myList1)
  25. print("The List after applying Selection Sort is : ")
  26. print(myList1)
Add Comment
Please, Sign In to add comment