原理:
快速排序也是分治法思想的一种实现,他的思路是使数组中的每个元素与基准值(Pivot,通常是数组的首个值,A[0])比较,数组中比基准值小的放在基准值的左边,形成左部;大的放在右边,形成右部;接下来将左部和右部分别递归地执行上面的过程:选基准值,小的放在左边,大的放在右边。。。直到排序结束。
步骤:
1.找基准值,设Pivot = a[0]
2.分区(Partition):比基准值小的放左边,大的放右边,基准值(Pivot)放左部与右部的之间。
3.进行左部(a[0] - a[pivot-1])的递归,以及右部(a[pivot+1] - a[n-1])的递归,重复上述步骤。
效果:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Sort : MonoBehaviour
{
// Use this for initialization
void Start()
{
List<int> list = new List<int>(){42,20,17,27,13,8,17,48};
QuickSort(list, 0, 7);
Debug.Log("sth");
}
// Update is called once per frame
void Update()
{
}
public void QuickSort(List<int> sqList, int low, int high)
{
int i = low;
int j = high;
int tmp = sqList [low];
while (low < high)
{
while ((low < high) && (sqList[high] >= tmp))
{
--high;
}
sqList [low] = sqList [high];
if (low < high)
++low;
while ((low < high) && (sqList[low] <= tmp))
{
++low;
}
sqList [high] = sqList [low];
if (low < high)
--high;
}
sqList [low] = tmp;
if (i < low - 1)
{
QuickSort(sqList, i, low - 1);
}
if (low + 1 < j)
{
QuickSort(sqList, low + 1, j);
}
}
}