题目
对于一个int数组,请编写一个快速排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。
测试样例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
思路
快速排序,每次寻找一个中心点,中心店左边的数字小于它,右边的数字大于它。
代码
class QuickSort:
def partition(self, A, first, last):
tmp = A[first]
while first < last:
while first < last and A[last] >= tmp:
last -= 1
if first < last:
A[first] = A[last]
while first < last and A[first] <= tmp:
first += 1
if first < last:
A[last] = A[first]
A[first] = tmp
return first
def sort(self, A, first, last):
if first < last:
part = self.partition(A, first, last)
self.sort(A, first, part)
self.sort(A, part + 1, last)
def quickSort(self, A, n):
# write code here
self.sort(A, 0, n - 1)
return A

这篇博客介绍了如何使用快速排序算法对整数数组进行排序。详细解释了算法思路,即选取中心点,使得数组左边的元素小于中心点,右边的元素大于中心点。并给出了相应的代码实现。
3022

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



