Archive

Archive for June 10, 2021

Python: Sorting Algorithm.- 4-Selection


Learning : Python coding, Math, Algorithm,
Subject: Writing Selection Sorting Algorithm in Python

[NOTE: To keep the code as simple as we can, We WILL NOT ADD any user input Varevecations. Assuming that our user will Enter the right inputs.]

Sorting Algorithm is a way to sort a given list/Array of numbers, there are several sorting Algorithm as follow:
Type of Sorting Algorithm
1. Quick Sort. [Click to Read the Post.]
2. Bubble Sort. [Click to Read the Post.]
3. Merge Sort. [Click to Read the Post.]
4. Insertion Sort. [Click to Read the Post.]
5. Selection Sort. [Click to Read the Post.]
6. Heap Sort. [Click to Read the Post.]
7. Radix Sort. [Click to Read the Post.]
8. Bucket Sort. [Click to Read the Post.]

Here in this post we will write a function to take a given list and sort it then pass it back. We assume the user will enter a serial of numbers, that he want to sort, our function will sort it using Selection Sorting Algorithm and print out the original numbers and the sorted one.

Selection Sort Algorithm: In Selection Sort, we will apply coming Steps:
1. Select the Element (e) in Index i = 0.
2. Find the Smallest Element in the Array from Index i Until index = length of Array.
3. SWAP the Smallest number in the Array with the Element (e) in index i=0.
4. Select the Element (e) in index i = i+1.
5. Repeat the Algorithm from step 2, until i+1 > length of the Array.

In our Application we will have three Functions, one to collect the Array numbers from the user. [This is the main function in all our sort applications] here is the code

ali radwani ahradwani.com python project code selection sorting algorithm


We are calling this Function within the Main Selection Sort Function.
Now we will write the Selection Sort Function .

 # Selection Sorting Function

def selection_sort(arr):    
    
    for i in range (0,len(arr)):
        e = arr[i]
        s_ind = i
        for j in range (i,len(arr)):
            if arr[j] < e :
                e = arr[j]
                s_ind = j
        
        arr[i], arr[s_ind] = arr[s_ind], arr[i]        
    
    return arr       



We will have a copy of same Function with some print-statement to show the iterations and elements in each steps. Here is the code ..

ali radwani ahradwani.com python project code selection sorting algorithm

Here is screen shot of only three iteration of the Algorithm run-time..

ali radwani ahradwani.com python project code selection sorting algorithm


We Done !! .. Another coding for Sorting Algorithms, New one will be published in coming days..

… Have fun with Coding … 🙂

To Download my Python code (.py) files Click-Here



ali radwani ahradwani.com python projects codeFollow me on Twitter..

By: Ali Radwani