快速排序法

原理:

快速排序也是分治法思想的一种实现,他的思路是使数组中的每个元素与基准值(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);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值