快速排序(Quicksort)是对冒泡排序的一种改进。 快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package quicksort | |
func Sort[T constraints.Ordered](buf []T) { | |
quick(buf, 0, len(buf)-1) | |
} | |
func quick[T constraints.Ordered](a []T, l, r int) { | |
if l >= r { | |
return | |
} | |
i, j, key := l, r, a[l] //选择第一个数为key | |
for i < j { | |
for i < j && a[j] > key { //从右向左找第一个小于key的值 | |
j-- | |
} | |
if i < j { | |
a[i] = a[j] | |
i++ | |
} | |
for i < j && a[i] < key { //从左向右找第一个大于key的值 | |
i++ | |
} | |
if i < j { | |
a[j] = a[i] | |
j-- | |
} | |
} | |
//i == j | |
a[i] = key | |
quick(a, l, i-1) | |
quick(a, i+1, r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment