Archive

Posts Tagged ‘Algorithm’

Python: Sorting Algorithm (3. Merge Sort)

June 3, 2021 3 comments

Learning : Python coding, Math, Algorithm,
Subject: Writing Merge 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 Here]
2. Bubble Sort. [Click Here]
3. Merge Sort. [Click Here]
4. Insertion Sort. [Click Here]
5. Selection Sort. [Click Here]
6. Heap Sort. [Click Here]
7. Radix Sort. [Click Here]
8. Bucket Sort. [Click Here]

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 and print out the original numbers and the sorted one.

Merge Sort: Steps of Merge Sorting Algorithm are:

1. If the Array has 1 Element then return it.
2. If the givin Array has more than 1 Element then we Divide it into 2 Parts.
Left = from Element 0 T0 Element len(arr)//2
and Right = from Element len(arr)//2 To Element len(arr). And we keep repeating step 2 for each part.
3. Once we have All parts divided we tart merge them in a sorted order.

Coding: In this Post we will write the Function for Main-Mnu, another one to collect the Array [Not Sorted] Elements from the user, then we will write the Main Function, here we will have One to Divide the Array into parts and One to Merge the Element together again. And as we done with Quick & Bubble Sort projects we will have one Fast-Run Function and another one with Details Step-By-Step run to show the Algorithm.

NOTE: All the Code will be Available in the Download Page.

Let’s start with the Main-menu to list down three option were the user will select one among them, the menu options are: 1. Merge Sort Algorithm – Fast Run. & 2. Merge Sort Algorithm – Step By Step and the last one is 3. Exit.
Here is the code.

python code project main menu by Ali Radwani merge sort Algorithm

I will Not post the code for collecting the Array Element from the user [Find it in the .py file for this project]. Here is the code for merge_sort_divider Function, it takes two arguments the Array and the user_selection, so if the user selection is 2 (2. Merge Sort Algorithm – Step By Step) We will print-out the Dividing Steps and some other Text. [We are using If Statement to print-out Text lines]. Here is the Code ..

ali radwani python code merge sort algorithm



Now for merging function, for merging function we will have two copies, one as Fast-Run and another for Details to print-out the running Steps, this will make the Fast-Run Function short and easy to follow-up. So, here is the Fast-Run Function code for merge the two part of array returned from the merge_sort_divider. Here is the Code ..

Run time screen ..

ali radwani python code merge sort algorithm



End of Merge Sorting Algorithm.

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



Follow me on Twitter..

By: Ali Radwani

Python: Sorting Algoritm – Bubble Sort

June 1, 2021 3 comments

Learning : Python, Math, Algorithm
Subject: Sorting Algoritm – Bubble Sort

[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 of numbers, there are several sorting Algorithm as follow:
Type of Sorting Algorithm
Quick Sort. [Click to Read]
Bubble Sort.
Merge Sort. [Commeing Soon]
Insertion Sort. [Commeing Soon]
Selection Sort. [Commeing Soon]
Heap Sort. [Commeing Soon]
Radix Sort. [Commeing Soon]
Bucket Sort. [Commeing Soon]

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 and print out the original numbers and the sorted one.

Bubble Sort: Steps of Bubble Sorting Algorithm are:
1. We will select the First Number (Current number) in the list and Compare it with the next number in the list. (Compare list[0] and list[1])

2. If the Next Number in the list IS SMALLER than Current Number SWAP the Two, then compare the Current with the third number and so on.

2.2 If the Next Number in the list IS NOT SMALLER than Current Number, Then we LEFT the Current Number in it’s Position and will Set the Next number as the Current. And will start Comparing Again as Step 2 until the last number in the list.

3. When we reach the end of the list and we perform a SWAP, then we start again with First Element as STEP 1.

4. If we reach the end of the list Without any SWAP being made, then the list is ordered and the algorithm can stop.

Coding Starting with the Main Menu Function and a Function to ask the
User to enter the numbers in the list, here are those two Functions.

python code bubble sorting algorithm project by Ali Radwani doha qatar



And here is the Main code that will call the Menu and trigger the Functions based on the User selecting.

python code bubble sorting algorithm project by Ali Radwani doha qatar



Also we have the Function that will ask the user to Enter the Numbers for the List or Array to be sort.
All the code will be Available as a .py file in the Download Page [Click Here]

Now let’s see the code for Bubble Sorting Algorithm, we will have two version of the code, one for Fast-Run that takes the list and return it back as Sorted, and another one will be to show the Details Step By Step of applying the Algorithm. Both Functions are the same but the details one will have several print statements to show the steps, here I am posting the Fast-Run version.


Run Screen..




End of Bubble Sort Algorithm, hope you enjoy it.


.. Have Fun With Coding ..

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


Follow me on Twitter..

By: Ali Radwani

Python: Sorting Algorithm (1.Quick Sort)

May 23, 2021 8 comments

Learning : SQL, Python, sqlite, DataBase
Subject: Testing the SQL Join commands using Python.

Sorting Algorithm is a way to sort a given list of numbers, there are several sorting Algorithm as follow:
Type of Sorting Algorithm
Quick Sort.
Bubble Sort.
Merge Sort.
Insertion Sort.
Selection Sort.
Heap Sort.
Radix Sort.
Bucket Sort.

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 and print out the original numbers and the sorted one.

Quick Sort Steps of Quick Sorting Algorithm are:
1 – Save the first element of the list as pivot. We will call it as pv .
2 – Define Two variables i and j. We will call them as fc, lc fc will be 0 (first element position in the list) and lc will be the length of the list.(last element position in the list) .
3 – Increment fc until the number in the list in fc position is smaller or equal to pv (the first element).
4 – Decrement lc until the number in the list in lc position smaller than pv.

until list[j] < pivot then stop.
5 – If fc less than lc then we swap the two elements in the location of fc and lc. (SWAP list[fc] and list[lc]).

7 – Exchange the pivot element with list[j] element.

Coding First we will write a sort Menu for the project, we will have tree items to select from, Quick Sort Algorithm – Fast Run and Quick Sort Algorithm – Step By Step This will show sorting details.

 # Main Menu

def main_menu ():
    os.system('clear')
    
    print('\n\n',' '*5,'******************************')
    print(' '*5,' ***','  Sorting Algorithm ',' '*1,'***')
    print(' '*5,' ***','     Quick Sort     ',' '*1,'***')
    print(' '*5,' ***',' '*22,'***')
    print(' '*5,' ******************************\n\n')
    
    print(' '*7,'1. Quick Sort Algorithm - Fast Run.')
    print(' '*7,'2. Quick Sort Algorithm - Step By Step.')
    print(' '*7,'9. Exit.')
    
    user_choice = input('\n   Select your choice.  > ')
    return user_choice 



And this is the main code body that will call the menu and check the user selection ..

 # The Main application Body

while True:
    
    user_select = main_menu()

    if user_select == '1' :
        user_list = create_list()
        
        fpos = 0  # first position index
        lpos = len(user_list)-1  # last position index
        
        original_list = user_list 
        print('\n   The original List is: ',original_list)

        user_sorted_list = quick_sort(user_list,fpos,lpos)
        
        print('\n   DONE .. We Finish Sorting .. ')
        print('   The Sorted List is: > ',user_sorted_list)
        input('\n   ...Press any key to continue.  ')
    
    if user_select == '2' :
        user_list = create_list()
        
        print('\n   We will show the Quick Sorting Step By Step... \n')
        fpos = 0  # first position index
        lpos = len(user_list)-1  # last position index
        original_list = user_list

        print('\n   The Original List is: ',original_list)
        user_list = quick_sort_details(user_list,fpos,lpos)
        
        print('\n   DONE .. We Finish Sorting .. ')
        print('   The Sorted List is: > ',user_list)
        input('\n   ...Press any key to continue.  ')

    if user_select == '9' :
        break



Also we will have a Function to take the List of Elements from the user, the user input will be as a string, we will convert it to an integer List and will return it back.. Here is the code ..

 # Create the List

def create_list():
    print('\n   Enter the List Elements separated by SPACE, when Finish just Press Enter.')
    the_list = input('\n   Start Entering the Numbers in the List. >  ')
    
    # Convert user input to List
    the_list = the_list.split()        
    
    # Convert str list to int list  
    the_list = [int(each) for each in the_list]

    return the_list



Now let’s write the Quick_sort function, then we will duplicaet it and add some print statements to show sorting steps. So first the code for Quick Sort Algorithm – Fast Run. Here is the code ..

Screen shot of the Quick Sort Algorithm – Fast Run.
python project code Quick Sort Algorithm ali radwani



Running this Function will return the sorted list and display it on the screen, I thought it will be nice if we show the sorting process Step by Step, so I copy the same Function with adding some print-statement in-between .. here is the code and the run-output..

Screen shot of the Quick Sort Algorithm – Detail Run.
python project code Quick Sort Algorithm ali radwani



End of Sorting Algorithm (1.Quick Sort)

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



Follow me on Twitter..

By: Ali Radwani