荷兰国旗问题

给定一个数组arr,和一个数num,将数组中小于num的数放在左边,等于的放在中间,大于的放在右边

public class Netherlands {

    
    public static void sort(int [] arr , int L , int R , int num){
        int less = L-1;
        int more = R+1;
        int cur = L;
        while(cur < more) {
            if(arr[cur] < num) {
                swap(arr,cur++,++less);
            }else if(arr[cur] > num){
                swap(arr, cur, --more);
            }else {
                cur++;
            }
        }
    }
    
    public static void main(String[] args) {
        int[] arr = { 3, 44, 38, 5, 26, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48 };
        sort(arr,0 ,arr.length-1,26);
        Arrays.stream(arr).forEach(x -> System.out.print(x+" "));
    }
    
    public static void swap(int [] arr ,int a ,int b  ) {
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
    

}

 

posted @ 2019-09-19 10:26  踏月而来  阅读(295)  评论(0编辑  收藏  举报