冒泡 ,选择,二分查找

import cn.sinvie.common.exception.ApiException;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Optional;

@Slf4j
public class Tset {
    public static void main(String[] args) {
        log.info("值为:{}", test01(new int[]{1, 2, 3, 4, 6, 5}));
        log.info("值为:{}", test02(new int[]{1, 2, 3, 4, 6, 5}));
        log.info("值为:{}", test03(new int[]{11, 22, 22, 33, 2, 3}, 22));
        test04();
    }

    //冒泡
    private static int[] test01(int[] arr) {
        arr = Optional.ofNullable(arr).orElseThrow(() -> new ApiException("Input array is null"));
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }

    //选择
    private static int[] test02(int[] arr) {
        arr = Optional.ofNullable(arr).orElseThrow(() -> new ApiException("Input array is null"));
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {
                    int temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
        }
        return arr;
    }

    // 二分查找
    private static int test03(int[] arr, int num) {
        arr = Optional.ofNullable(arr).orElseThrow(() -> new ApiException("Input array is null"));
        arr = Arrays.stream(arr)
                .distinct()
                .sorted()
                .toArray();
        int min = 0;
        int max = arr.length - 1;
        int mid;
        while (min <= max) {
            mid = (min + max) / 2;
            if (arr[mid] > num) {
                max = mid - 1;
            } else if (arr[mid] < num) {
                min = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    // 打印99乘法表
    private static void test04() {
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + "*" + i + "=" + i * j + " ");
            }
            System.out.println();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值