Archive for July 8, 2021

Python Sorting Algorithm – Heap Sorting -P4

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 Last Parts (2 & 3) we wort the Following Functions:

  • Sections Header.
  • Main Menu Function.
  • Entering/Creating the Array.
  • Print-Out or to Display the Array.
  • Check If Array in Max-Heap.
  • Convert Array to Max-Heap.

In this Part-4 we will cover another Two important Functions that we need to talk about in our mission to understand the Heap Sorting Algorithm. In a Max-Heap Array we may need to Add new Node to the Array and we may need to Delete a Node. Also I just add Item No.7 style=”color:#2662ee;”>print(‘ ‘*5,’ 7. Start Heap Sorting.’) to the main-menu so we can do Heap Sorting to a given Array.

Starting with Add New Node, Simply we Add the Node to the end of the Array using arrat.append(new_node) then we need to Check If still the Array in Max-Heap If NOT, We MUST Convert it to a Max-Heap.

Scope of Work Ask the user to Enter the New Node Value, Add The Node to the End of the Array, in While Loop Call convert_to_max_heap (arr,True), check_if_max_heap (arr,True) as following:
while not is_max:
arr = convert_to_max_heap (arr,True)
is_max = check_if_max_heap (arr,True)
this will keep check and convert the Array to Max-Heap. Here is the Full code and run screen ..

ali radwani python project code heap sorting
ali radwani python project code math algorithm doha qatar

Now we will write a Function to Delete a Node from the Max-Heap Array. Deleting a Node is just by removing the first node in the Array (Array[0]), then moving the last element in the Array to it’s position, by doing this we may not having a Max-Heap Array any-more, so we need to convert the array to a Max-Heap. In our application here, we will have a while loop and calling the functions (check_if_max_heap and convert_to_max_heap) until we have the Array in a Max-Heap. Here is the code ..

We will stop here in this part. In Part-5 we will Sort any Array using the Max-Heap Sort Algorithm.

..:: Have Fun with Coding ::.. 🙂

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

ali radwani python projects codeFollow me on Twitter..

By: Ali Radwani