像合并排序一样,QuickSort是一种分而治之算法。它选择一个元素作为枢轴,并围绕拾取的枢轴对给定的数组进行分区。 quickSort有许多不同的版本,它们以不同的方式选择枢轴。
- 始终选择第一个元素作为枢轴。
- 始终选择最后一个元素作为枢轴(在下面实现)
- 选择一个随机元素作为枢轴。
- 选择中位数作为枢轴。
quickSort中的关键过程是partition()。分区的目标是,给定一个数组和一个数组元素x作为枢轴,将x放在排序数组中的正确位置,并将所有较小的元素(小于x)放在x之前,并将所有较大的元素(大于x)放在之后X。所有这些都应在线性时间内完成。
递归QuickSort函数的伪代码:
/* low --> Starting index, high --> Ending index */
quickSort(arr[], low, high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
pi = partition(arr, low, high);
quickSort(arr, low, pi - 1); // Before pi
quickSort(arr, pi + 1, high); // After pi
}
}
Python
# Python program for implementation of Quicksort Sort
# This function takes last element as pivot, places
# the pivot element at its correct position in sorted
# array, and places all smaller (smaller than pivot)
# to left of pivot and all greater elements to right
# of pivot
def partition(arr, low, high):
i = (low-1) # index of smaller element
pivot = arr[high] # pivot
for j in range(low, high):
# If current element is smaller than or
# equal to pivot
if arr[j] <= pivot:
# increment index of smaller element
i = i+1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return (i+1)
# The main function that implements QuickSort
# arr[] --> Array to be sorted,
# low --> Starting index,
# high --> Ending index
# Function to do Quick sort
def quickSort(arr, low, high):
if len(arr) == 1:
return arr
if low < high:
# pi is partitioning index, arr[p] is now
# at right place
pi = partition(arr, low, high)
# Separately sort elements before
# partition and after partition
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
# Driver code to test above
arr = [10, 7, 8, 9, 1, 5]
n = len(arr)
quickSort(arr, 0, n-1)
print("Sorted array is:")
for i in range(n):
print("%d" % arr[i]),
# This code is contributed by Mohit Kumra
#This code in improved by https://github.com/anushkrishnav
请参阅有关QuickSort的完整文章以了解更多详细信息!