基于荷兰国旗的快速排序

基于荷兰国旗的快速排序

重拾

package util;

import javafx.util.Pair;

import java.util.Arrays;
import java.util.Random;

public class QuickSort {
    
    
    //荷兰国旗
    private static Pair<Integer, Integer> partition(int[] arr,int left,int right){
    
    
        int pivot = arr[right];
        int less = left - 1;        // index <= less的元素 均 < pivt
        int more = right + 1;       // index >= more的元素 均 > pivt
        while(left < more){
    
    
            if(arr[left] < pivot){
    
    
                int temp = arr[left];
                arr[left++] = arr[++less];
                arr[less] = temp;
            }else if(arr[left] > pivot){
    
    
                int temp = arr[left];
                arr[left] = arr[--more];
                arr[more] = temp;
            }else{
    
    
                ++left;
            }
        }
        //这样(less,more)之前的元素都是pivot
        return new Pair<>(less,more);
    }
    private static void quickSort(int[] arr,int left,int right){
    
    
        if(left >= right){
    
    
            return;
        }else{
    
    
            Pair<Integer,Integer> pair = partition(arr,left,right);
            quickSort(arr, left, pair.getKey());
            quickSort(arr, pair.getValue(), right);
        }
    }
    public static void quickSort(int[] arr){
    
    
        if(arr != null && arr.length > 1) {
    
    
            quickSort(arr, 0, arr.length - 1);
        }
    }
    public static void main(String[] args) {
    
    
        Random random = new Random();
        int[] arr = new int[15];
        for (int i = 0; i < arr.length; ++i){
    
    
            arr[i] = random.nextInt()%100;
        }
        Arrays.stream(arr).forEach(val-> System.out.print(val + " "));
        System.out.println();

        quickSort(arr);

        Arrays.stream(arr).forEach(val-> System.out.print(val + " "));
        System.out.println();
    }
}

output

52 52 39 -42 87 -77 -37 89 -98 -32 87 -34 82 -67 42 
-98 -77 -67 -42 -37 -34 -32 39 42 52 52 82 87 87 89 

猜你喜欢

转载自blog.csdn.net/xiaolixi199311/article/details/106345251