算法

😀

1到100之间的偶数之和

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//方法一
var sum =0;
for (int i = 2; i <= 100; i+=2) {
sum+=i;
}
System.out.println(sum);

//方法二
var s=0;
var a=1;
var b=100;
for (; a <= b; a++) {
s+=a%2==0?a:0;
}
System.out.println(s);

逢七过

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//方法一
for (int i = 0; i < 100; i++) {
if (i % 10 == 7 || i / 10 % 10 == 7 || i % 7 == 0) {
System.out.println("过");
continue;
}
System.out.println(i);
}

//方法二
for (int i = 0; i < 100; i++) {
String d = (i % 10 == 7 || i / 10 % 10 == 7 || i % 7 == 0 ? "过" : String.valueOf(i));
System.out.println(d);
}

求和

1
2
3
4
5
6
List<Integer> list = List.of(1, 2, 3, 4, 5, 6);
var sm =0;
for (int i = 0; i < list.size(); i++) {
sm+=list.get(i);
}
System.out.println(sm);

二分半查找

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Test
public void test(){
int[] arr = {1, 2, 3, 4, 5, 6, 7};
System.out.println(bina(arr, 4));
}
private static int bina(int[]arr,int number) {
var min=0;
var max=arr.length-1;

while (true) {
if (min > max) {
return -1;
}
int mid =(min+max)/2;
if (arr[mid] > number) {
max=mid-1;
} else if (arr[mid] < number) {
min = mid + 1;
} else {
return mid;
}
}
}

冒泡排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
public void test1(){
int[] arr = {2, 5, 3, 4, 1};
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;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
}

选择排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
public void test2(){
int[] arr = {2, 3, 1, 5, 4};

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[i];
arr[i] = arr[j];
arr[j]=temp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}

}