#Unity _ 快速排序


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class 快速排序 : MonoBehaviour
{
    void Start()
    {
        快速排序Test(arr, 0, arr.Length - 1);
    }
    public int[] arr = new int[] { 1, 3, 2, 4, 5, 8, 7, 22, 32, 18, 17, 43, 21, 33 };
    public void 快速排序Test(int[] arr, int left, int right)
    {
        if (left >= right)
        {
            return;
        }
        int leftIndex = left;
        int rightIndex = right;
        int midIndex = left;
        int temp;
        
        while (leftIndex < rightIndex)
        {
            while (leftIndex < rightIndex && arr[rightIndex] >= arr[midIndex])
            {
                rightIndex--;
            }
            temp = arr[midIndex];
            arr[midIndex] = arr[rightIndex];
            arr[rightIndex] = temp;
            midIndex = rightIndex;

            while (leftIndex < rightIndex && arr[leftIndex] <= arr[midIndex])
            {
                leftIndex++;
            }
            temp = arr[midIndex];
            arr[midIndex] = arr[leftIndex];
            arr[leftIndex] = temp;
            midIndex = leftIndex;
        }
        快速排序Test(arr, left, midIndex - 1);
        快速排序Test(arr, midIndex + 1, right);
    }
}

上一篇:LeetCode31. 下一个排列


下一篇:力扣 - 剑指 Offer 53 - I. 在排序数组中查找数字 I