Home > Learning, Lesson, Problem, Projects/Experiments, Python > Python Sorting Algorithm – Heap Sorting -P2

Python Sorting Algorithm – Heap Sorting -P2


Learning : Python, Math, Algorithm
Subject: Sorting Algorithm, Heap Sort P2

[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.]

In this post we will start writing some codes for the Heap Sorting application, we will start with the following Functions:

  • Main Menu Function.
  • Entering/Creating the Array.
  • Print-Out or to Display the Array.
  • Sections Header.


So First: We will start with the Main_menu Function and will return user_choice also the main application body.. Here is the code ..

 # Main Menu function and the main application body..

    
def main_menu():
    os.system('clear')
    header()
    print("\n\n"," "*4,"==============[ Main Menu ]==============\n")
    print(' '*5,' 1. Enter the Binary Tree as an Array.')
    print(' '*5,' 2. Print out the Binary Tree. {Text Mode}')
    print(' '*5,' 3. Check if it is a Max Heap.')
    print(' '*5,' 4. Convert an Array (Binary Tree) to a Max-Heap.')
    print(' '*5,' 5. Add New Node to the Binary Tree.')
    print(' '*5,' 6. Delete a Node From the Binary Tree.')
    print(' '*5,' 9. Exit.')

    user_choice = input("\n Select from the Menu: > ") 

    return user_choice


# This is the Main application body.
while True :

    user_select = main_menu()

    if user_select == '1' :
        print(' Enter the Binary Tree as a Array.') 
        arr = create_array_node_b_node()
        
    if user_select == '2' : 
        try:
            print_bt_text (arr)
        except :           
            input('\n   You Must First Enter/Create the Array... Press any key then Select Option 1. > ')
    
    if user_select == '3' :
        print(' Check if the Array is a Max Heap.') 
        
        
    if user_select == '4' :
        print(' Convert an Array (Binary Tree) to a Max-Heap.') 


    if user_select == '5' :
        print(' Add New Node to the Binary Tree.') 
        #add_node(arr)

    if user_select == '6' :
        print(' Delete a Node from the Binary Tree.') 
        #delete_node(arr)

    if user_select == '9' :
        print('\n\n   Thank you for using this Appliation. ')
        input('\n         Press any key .. ')
        break
    


Next we will write the function def create_array_node_b_node() in this function the user will start to enter the nodes in the Heap Tree starting from the Root and level-by-level. With every/each Node if the user just press Enter the Node will be as None,then will ask the user if there is any more nodes in the level and if the user answer with [N] then we will complete the level with None. Also in starting of each level we will ask the user if there is any more Nodes remain in the level.
Here is the code ..

ali radwani ahradwani.com python code algorithm heap sorting project



In the last Function in this part, we will print-out the Heap-Array as text of Parents and Childs. Here is the code ..

 # Function to print-out the Heap-Array Tree

def print_bt_text (arr):
    """
        Function will Write/Print-out the Tree as Text Showing the Parents and the Childs.
        
        Arguments: The Array as arr
        
        return None  
    """    
    os.system('clear')
    header()
    print("\n\n==========[ Print out the Binary Tree. {Text Mode} ]==========\n\n")
    
    print('   The array we Have is: ',arr)
   
    for x in range (0,len(arr)):
        print(' ')      
        if arr[x] != None :
      
            try:  # For left childs
                l_child = 2 * x + 1
                
                if arr[l_child] != None :
                    print(f'   Parent Node ({arr[x]}) has a Left Child ({arr[l_child]})',end="") 
                    
                elif arr[l_child] == None:    
                    print(f'   Parent Node ({arr[x]}) has NO Left Child',end="")    
            except:
                pass
                
            try:   # For right Childs
                r_child = 2 * x + 2
                
                if (arr[l_child] == None) and (arr[r_child] != None) :
                    print(f' But it Has a Right Child ({arr[r_child]}).')
        
                elif (arr[l_child] != None) and (arr[r_child] != None) :
            
                    print(f' and a Right Child ({arr[r_child]})')
                    
                elif (arr[r_child] == None):
                    print(f' and Has NO Rigth Child.')
            except:
                pass
                
    input('   DONE ... Here is a Print out of the Heap Tree Array in {Text Mode}')



We will stop here in this part and will do more Functions in Part 3

..:: 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

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s