Python Program for Quick Sort
In this tutorial, we will discuss a Python program for a quick sort algorithm to sort an array of numbers in ascending order.
Before going to the program first, let us understand what is Quick Sort.
Quick Sort:
- Quick sort is an efficient, divide-and-conquer sorting algorithm that selects a “pivot” element and partitions the array into two sub-arrays based on whether the elements are less than or greater than the pivot.
Related: Python program for insertion sort
Program code for Quick Sort in Python
# Quick Sort in Python def partition(arr, low, high): pivot = arr[high] i = low - 1 for j in range(low, high): if arr[j] <= pivot: i += 1 arr[i], arr[j] = arr[j], arr[i] arr[i + 1], arr[high] = arr[high], arr[i + 1] return i + 1 def quick_sort(arr, low, high): if low < high: pi = partition(arr, low, high) quick_sort(arr, low, pi - 1) quick_sort(arr, pi + 1, high) arr = [10, 7, 8, 9, 1, 5] quick_sort(arr, 0, len(arr) - 1) print("Sorted array:", arr)
Explanation
- Function Definitions: The
partition
function partitions the array into two sub-arrays based on the pivot element, and thequick_sort
function sorts the array using the quick sort algorithm. - Main Program: The program defines an unsorted array and sorts it using the
quick_sort
function. It then prints the sorted array.
Output
- When you run the above program, it will sort the array using quick sort and print the sorted result.
Conclusion
- In this tutorial, we learned how to implement the quick sort algorithm in Python.
- Understanding this concept is essential for solving various sorting problems and enhancing your programming skills.