Quick Sort
- 首先设定一个分界值,通过该分界值将数组分成左右两部分。
- 将大于等于分界值的数据集中到数组右边,小于分界值的数据集中到数组的左边。此时 ,左边部分中各元素都小于等于分界值,而右边部分中各元素都大于等于分界值。
- 然后,左边和右边的数据可以独立排序。对于左侧的数组数据,又可以取一个分界值,将该部分数据分成左右两部分,同样在左边放贯较小值,右边放置较大值。右侧的数组数据也可以做类似处理。
- 重复上述过程,可以看出,这是一个递归定义。通过递归将左侧部分排好序后,再递归排好右侧部分的顺序。当左、右两个部分各数据排序完成后,整个数组的排序也就完成了
#include <iostream>
#include <cstdlib>
#include <cmath>
const int SIZE = 10;
int main()
{
void QuickSort(int *a, int left, int right);
int array[SIZE], i;
srand(time(NULL));
for (i=0;i<SIZE;i++)
{
array[i] = rand()/1000+10;
}
std::cout << "排序前的数组为:" << std::endl;
for (i=0;i<SIZE;i++)
{
std::cout << array[i] << " ";
}
std::cout << std::endl;
QuickSort(array, 0, SIZE-1);
std::cout << "排序后的数组为:" << std::endl;
for (i=0;i<SIZE;i++)
{
std::cout << array[i] << " ";
}
std::cout << std::endl;
return 0;
}
void QuickSort(int *a, int left, int right)
{
int f, t;
int ltemp, rtemp;
ltemp = left;
rtemp = right;
f = a[(left+right)/2];
while (ltemp<rtemp)
{
while (a[ltemp]<f)
{
++ltemp;
}
while (a[rtemp]>f)
{
--rtemp;
}
if (ltemp<=rtemp)
{
t = a[ltemp];
a[ltemp] = a[rtemp];
a[rtemp] = t;
--rtemp;
++ltemp;
}
}
if (ltemp==rtemp)
{
ltemp++;
}
if (left<rtemp)
{
QuickSort(a,left, ltemp-1);
}
if (ltemp<right)
{
QuickSort(a, rtemp+1, right);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9748ee4398c8ee4b6f2733088136caf3.png)
import numpy as np
def QuickSort(value, left, right):
"""
Qucik Sort
:param value: random array
:param left: start
:param right: end
:return: quick array
"""
if left >= right:
return
mid = value[left]
ltemp = left
rtemp = right
while (ltemp < rtemp):
while (ltemp < rtemp and value[rtemp] >= mid):
rtemp -= 1
value[ltemp] = value[rtemp]
while (ltemp < rtemp and value[ltemp] < mid):
ltemp += 1
value[rtemp] = value[ltemp]
value[ltemp] = mid
QuickSort(value, left, ltemp - 1)
QuickSort(value, ltemp + 1, right)
def main():
list = np.random.randint(100, size=10)
print("排序前的数组为: ")
print(list)
left = 0
right = len(list) - 1
QuickSort(list,left,right)
print("排序后的数组为: ")
print(list)
if __name__ == "__main__":
main()
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0d9dbfe5e99782827f7b453d0c85f1df.png)