快速排序和二分法查找

二分法
https://blog.csdn.net/qq_42676052/article/details/84258755

快速排序
https://blog.csdn.net/as02446418/article/details/47395867

import java.util.Arrays;

/**

  • @author Pstart
  • @create 2019-11-09 10:12
    /
    /
  • 快速排序
  • 以基准量为起点,从数组最右边开始找小于基准量的数
  • 从数组最左边找大于基准量的数
  • 彼此替换,在相遇点
  • 将值与基准量比较,小于基准量则替换
  • 对原基准量的左边和右边递归使用quickSortLeft方法
  • 右边选择的是中间值做基准量
  • */

public class QuickSort {
public static void quickSortLeft(int[] arr, int min, int max) {

    int pull, push, temp, base;
    if (min > max) {
        return;
    }
    pull = max;
    push = min;
    base = arr[min];
    while (push < pull) {
        for (; base <= arr[pull] && push < pull; ) {
            pull--;
        }
        for (; base >= arr[push] && push < pull; ) {
            push++;
        }
        if (push < pull) {
            temp = arr[pull];
            arr[pull] = arr[push];
            arr[push] = temp;
        }

    }
    arr[min] = arr[push];
    arr[push] = base;
    //左
    quickSortLeft(arr, min, pull - 1);
    //右
    quickSortLeft(arr, pull + 1, max);
}


//折半查找
public static int binary(int[] arr, int arrayLength, int key) {
    int init = 0;
    int max = arrayLength;
    while (init <= max) {//1,2,3,4,5 找1,找5
        int middle = (init + max) / 2;
        if (key == arr[middle]) {
            return middle;
        } else if (key < arr[middle]) {
            max = middle - 1;//1/2=0
        } else {
            init = middle + 1;
        }
    }
    return -1;
}

//二分查找的递归写法
public static int binaryRecursive(int[] arr, int init, int arrayLength, int key) {
    int middle = (init + arrayLength) / 2;
    if (init>arrayLength){
            return -1;
    }
    if (key < arr[middle]) {
        return binaryRecursive(arr, init, arrayLength - 1, key);
    } else if (key > arr[middle]) {
        return binaryRecursive(arr, init, arrayLength + 1, key);
    } else{
        return middle;
    }
}

public static void main(String[] args) {
    int[] arr = {3, 8, 0, 7, -9, 2, 9, -1, 20};
    int mark = 0;
    int arrLength = arr.length - 1;
    quickSortLeft(arr, mark, arrLength);
    System.out.println("快速排序后-" + Arrays.toString(arr));

    if (binary(arr, arrLength, -1) != -1) {
        System.out.println("二分法查找值(-1)索引=" + binary(arr, arrLength, -1));
        System.out.println("递归二分法查找值(-1)索引=" + binaryRecursive(arr, mark, arrLength, -1));
    }
}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值