快速排序

#include <iostream>

using namespace std;
void QuickSort(int *array,int left,int right)
{
    if(left>=right)
    {
        return;
    }
    else
    {
        int Base=array[left];
        int low=left;
        int high=right;

        while(low<high)
        {
            while(array[high]>=Base&&low<high)
            {
                high--;
            }
            array[low]=array[high];

            while(array[low]<=Base&&low<high)
            {
                low++;
            }
            array[high]=array[low];

        }
        array[low]=Base;
        QuickSort(array,left,low-1);
        QuickSort(array,low+1,right);
    }

}

int main()
{
    int array[]= {2,5,8,9,1,5,6,2};
    QuickSort(array,0,7);
    for(int i=0; i<=7; i++)
        cout<<array[i];
    return 0;
}

java版本

class Solution {
    public void quickSort(int[] nums,int low,int high) {
        if(low<high) {
            int index=partition(nums,low,high);
            quickSort(nums,low,index-1);
            quickSort(nums,index+1,high);
        }
    }
    public int partition(int[] nums,int low,int high){
        int pivot=nums[low];
        while(low<high)
        {
            while(low<high && nums[high]>=pivot)
            {
                high--;
            }
            if(low<high){
                nums[low]=nums[high];
            }
            while(low<high && nums[low]<=pivot)
            {
                low++;
            }
            if(low<high){
                nums[high]=nums[low];
            }
        }
        nums[low]=pivot;
        return low;
    }
    public int[] sortArray(int[] nums) {
        quickSort(nums,0,nums.length-1);
        return nums;
    }
}
posted @ 2021-09-11 10:33  帅气的涛啊  阅读(36)  评论(0编辑  收藏  举报