Showing posts with label Sort. Show all posts
Showing posts with label Sort. Show all posts

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)

Functions - Insertion sort

# Functions - Insertion 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 - Insertion sort
def fn_Ins_Sort(L):
    for idx in range(1, len(L), 1):
        while( idx>0 and L[idx-1]>L[idx] ):
            L[idx],L[idx-1] = L[idx-1],L[idx]
            idx = idx-1

    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_Ins_Sort(L1)
print("Sorted List :", L1)