How to Sort in Ascending Order using Quicksort in Python

In this tutorial, we will program 'How to Sort in Ascending Order using Quicksort in Python.' We will learn how to sort a list in ascending order. The objective is to teach you how to sort a list using the Quicksort algorithm. I will provide a sample program to demonstrate the actual coding process in this tutorial.

This topic is very easy to understand. Just follow the instructions I provide, and you can do it yourself with ease. The program I will show you covers the basics of programming to sort a list in ascending order. I will do my best to provide you with a simple method for sorting a list. So, let's start with the coding.

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. def quicksort(arr):
  2. if len(arr) <= 1:
  3. return arr
  4. else:
  5. pivot = arr[0]
  6. left = [x for x in arr[1:] if x < pivot]
  7. right = [x for x in arr[1:] if x >= pivot]
  8. return quicksort(left) + [pivot] + quicksort(right)
  9.  
  10. ret = False
  11.  
  12. while True:
  13. print("\n================== Sort in Ascending Order using Quicksort ==================\n\n")
  14.  
  15.  
  16. arr = [-1, -3, 2, 8, 5, 0, 10, 9, -2]
  17. sorted_arr = quicksort(arr)
  18.  
  19. print("Original Order: ",arr)
  20. print("\n")
  21. print("Ascending Order:", sorted_arr)
  22.  
  23. opt = input("\nDo you want to try again?(yes/no): ")
  24.  
  25. if opt.lower() == 'yes':
  26. ret=False
  27. elif opt.lower() == 'no':
  28. ret=True
  29. print("Exiting program....")
  30.  
  31. else:
  32. print("Please enter yes/no:")
  33. break
  34.  
  35. if ret == False:
  36. continue

This script sorts the array [-1, -3, 2, 8, 5, 0, 10, 9, -2] in ascending order using the quicksort algorithm. It repeatedly prompts the user to rerun the sorting process or exit the program. Each time, it prints the original array and its sorted version, allowing the user to choose whether to continue or exit based on their input.

Output:

There you have it we successfully created How to Sort in Ascending Order using Quicksort in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials

Add new comment