Java 实现 Quicksort 和 Selection

Java 实现 Quicksort 和 Selection

QuickSort

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

public class Quicksort {
    private static int partition(int[] arr, int low, int high) {
        Random rand = new Random();
        int pivot_i = rand.nextInt((high-low))+low; // randomized in certain area, notice it has to in range of low and high
        int pivot = arr[pivot_i];
        arr[pivot_i] = arr[high];
        arr[high] = pivot;
        int i = low - 1;
        for (int j = low; j <= (high - 1); j++) {
            if (arr[j] <= pivot) {
                int tmp2 = arr[++i];
                arr[i] = arr[j];
                arr[j] = tmp2;
            }
        }
        arr[high] = arr[++i];
        arr[i] = pivot;
        return i;
    }

    public static void quicksort(int[] arr, int low, int high) {
        if (low < high) {
            int q = partition(arr, low, high);
            quicksort(arr, low, q - 1);
            quicksort(arr, q + 1, high);
        }
    }

    public static void main(String args[]) {
        int[] i = {1, 2, 3, 8, 0, 0, 89, 33, 48, 90, -89, 48};
        quicksort(i, 0, i.length-1);
        System.out.println(Arrays.toString(i));
    }
}

Selection

import java.util.Random;

public class Selection {
    private static int partition(int[] arr, int low, int high){
        Random rand = new Random();
        int pivot_i = rand.nextInt(high-low) + low;
        int pivot = arr[pivot_i];
        arr[pivot_i] = arr[high];
        arr[high] = pivot;
        int i = low - 1;
        for (int j = low; j <= high-1; j++){ // notice the bound
            if (arr[j] <= pivot){
                int tmp = arr[++i];
                arr[i] = arr[j];
                arr[j] = tmp;
            }
        }
        arr[high] = arr[++i];
        arr[i] = pivot;
        return i;
    }

    public static int selection(int[] arr, int low, int high, int i){
        if (low == high){
            return arr[low];
        }
        int q = partition(arr, low, high);
        int k = q - low  + 1;
        if ( i == k ) return arr[q];
        else if (i < k) return selection(arr, low, q-1, i);
        else return selection(arr, q+1, high, i-k);
    }

    public static void main(String args[]) {
        int[] i = {1, 6, -9023, 234, 345, 898, 234, 565, 4, 2, 3,0,7};
        int x = 1;
        while ( x <= i.length) {
            System.out.println(selection(i, 0, i.length - 1, x));
            x++;
            }
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值