Showing posts with label selection sort. Show all posts
Showing posts with label selection sort. Show all posts

Selection sort

Selection Sort


Algorithm: Selection Sort

Input: A list of n numbers that are not sorted

Output: The list arranged in increasing (ascending) order

________________________________________

Steps

  1. Start
  2. Take the list of numbers.
  3. Begin with the first position in the list.
  4. Repeat the following steps until the second last position:
    1.        Assume the value at the current position is the smallest.
    2.        Look through all the numbers to the right to find the actual smallest value.
    3.        If you find a number smaller than the assumed value, remember its position.
    4.        If the smallest value is not already in the current position, swap the two values.
    5.        Move to the next position and repeat.
  5. When finished, the list will be sorted.
  6. Show the sorted list.
  7. Stop

 


# Selection sort


def fnSelectionsort(L):

for i in range(0,len(L)-1):

min_pos=i

min_ele=min(L[i+1:])

if(L[min_pos] > min_ele):

min_ele_pos = L.index(min_ele)

L[min_pos],L[min_ele_pos]=L[min_ele_pos],L[min_pos]

L = eval(input("Enter list of elements : "))

fnSelectionsort(L)

print(L)


"""

Sample output

>python Selectionsort.py

Enter list of elements : [34, 8, 64, 51, 32, 21]

[8, 21, 32, 34, 51, 64]

"""

Functions - Selection Sort

# Functions - Selection sort

# Function - Read list of elements
def fn_read(nterms):
    L = []
    for idx in range(0, nterms, 1):
        ele = int(input("Enter element : "))
        L.append(ele)
    return L

# Function - Selection sort
def fn_Selection_Sort(L):
    for idx in range(0, len(L)-1, 1):
        min_ele = min(L[idx:len(L)])
        pos = L.index(min_ele)
        if(pos != idx):   
            L[pos], L[idx]  = L[idx], L[pos]
    return L
   
# Main Program
# Read elements and create list
no_of_terms = int(input("Enter number of terms : "))
L1 = fn_read(no_of_terms)

print("Original list :", L1)
L1 = fn_Selection_Sort(L1)
print("Sorted List :", L1)

Sorting - Selection sort

# Selection sort

# Read elements and create list

no_of_terms = int(input("Enter number of terms : "))
List1 = []

for idx in range(0, no_of_terms, 1):
    ele = int(input("Enter element : "))
    List1.append(ele)

print("Original list :", List1)

for idx in range(0, len(List1)-1, 1):
    min_ele = min(List1[idx:len(List1)])
    pos = List1.index(min_ele)
    if(pos != idx):   
        List1[pos], List1[idx]  = List1[idx], List1[pos]
       
print("Sorted List :", List1)