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();
}
}
}
冒泡 ,选择,二分查找
于 2023-08-22 18:22:27 首次发布