Quicksort is a divide and conquer algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays. The steps are:
- Pick an element, called a pivot, from the array.
- Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
- Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.
快排的核心在于分治 (Divide and conquer) 和(原地)分区 (Partition),先在数组中选择一个数字 (基准值 pivot),把数组中的数字分为两部分,比 pivot 小的数字移到数组左边,比 pivot 大的数字移到数组的右边。
Time Complexity: best O(nlogn), average O(n log(n)), worst O(n^2)
Space Complexity: O(1)
def quick_sort(arr):
arr = quick_sort_recur(arr, 0, len(arr) - 1)
return arr
def quick_sort_recur(arr, first, last):
if first < last:
pivot = partition(arr, first, last)
quick_sort_recur(arr, first, pivot - 1)
quick_sort_recur(arr, pivot + 1, last)
return arr
def partition(arr, first, last):
wall = first
for pos in range(first, last):
if arr[pos] < arr[last]: # last is the pivot
arr[pos], arr[wall] = arr[wall], arr[pos]
wall += 1
arr[wall], arr[last] = arr[last], arr[wall]
return wall

快速排序是一种分治策略的算法,通过选取基准值并进行分区操作,将数组分为小于和大于基准值的两部分,然后递归地对这两部分进行排序。在最好的情况下,时间复杂度为O(nlogn),平均情况也为O(n log(n)),最坏情况为O(n^2),空间复杂度为O(1)。
1595

被折叠的 条评论
为什么被折叠?



