1.选择排序法与冒泡排序法
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42public class Test { public static void main(String[] args) { int[] arraytest = { 1 , 9 , 9 , 0 , 9 , 6 , 0 , 5 } ; for (int i = 0; i < arraytest.length; i++) { System.out.print(arraytest[i]+" "); } System.out.println(); // new Test().selectsort(arraytest); new Test().pullsort(arraytest); for (int i = 0; i < arraytest.length; i++) { System.out.print(arraytest[i]+" "); } } public void selectsort(int[] arraytest){ int temp ; for (int i = 0; i < arraytest.length; i++) { for (int j = i+1; j < arraytest.length; j++) { //依次与后面的数比较,最后把最小的数交换 if(arraytest[j]<arraytest[i]){ temp = arraytest[i] ; arraytest[i] = arraytest[j]; arraytest[j] = temp ; } } } } public void pullsort(int[] arraytest){ int temp ; for (int i = 0; i < arraytest.length; i++) { for (int j = 0; j < arraytest.length-i-1; j++) { //把相邻两个数据比较 if(arraytest[j]>arraytest[j+1]){ //看是从大到小排序还是从小到大排序看temp的值赋给了谁,所以这里是从小到大排序 temp = arraytest[j] ; arraytest[j] = arraytest[j+1] ; arraytest[j+1] = temp ; } } } } }
2.二分法查找
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15public class SplitBy2{ static int num=12; static int[] arr={1,3,7,11,12,17,23,25,27}; static int start,end,index; public static void main(String[] args){ System.out.println(splitBy2(arr,num)); } public static int splitBy2(int arr[],int num){
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36start=0; end=arr.length-1; while(true){ index=(start+end)/2; if(arr[index]==num){ return index; }else if(start>end){ System.out.println("没有找到"); return -1; }else{ if(arr[index]>num){ end=index-1; } if(arr[index]<num){ start=index+1; } } } } }
最后
以上就是彩色茉莉最近收集整理的关于JAVA最简单算法题合集的全部内容,更多相关JAVA最简单算法题合集内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复