Quick sort is a highly efficient sorting algorithm that uses the divide-and-conquer approach. It works by selecting a 'pivot' element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively. Quick sort is known for its performance and efficiency, with an average-case time complexity of O(n log n).
Consider an array with the following elements:
[10, 7, 8, 9, 1, 5]
To sort this array using quick sort, follow these steps:
Let's apply these steps to the example array:
Below is the pseudo code for the quick sort algorithm:
function quickSort(array, low, high)
if low < high then
pivotIndex = partition(array, low, high)
quickSort(array, low, pivotIndex - 1)
quickSort(array, pivotIndex + 1, high)
end if
end function
function partition(array, low, high)
pivot = array[high]
i = low - 1
for j = low to high - 1 do
if array[j] < pivot then
i = i + 1
swap(array[i], array[j])
end if
end for
swap(array[i + 1], array[high])
return i + 1
end function
Explanation:
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i = 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)
# Example usage:
array = [10, 7, 8, 9, 1, 5]
print("Original array:", array)
quick_sort(array, 0, len(array) - 1)
print("Sorted array:", array) # Output: [1, 5, 7, 8, 9, 10]
This Python program defines functions to perform quick sort on an array. The partition function rearranges the elements based on the pivot, and the quick_sort function recursively sorts the sub-arrays.