第一题: import java.lang.Integer; import java.util.Arrays; class ArrDemo{ public static void main(String[] args){ int[] arr = new int[]{1,20,60,90,4}; //int[] arr = new int[5];//问题2、这个值并没有在错误判断里面,怎么判断? System.out.println(Arrays.toString(arr)); int maxv = getMax(arr); System.out.println(maxv); } public static int getMax(int[] arr){ int length = arr.length; if(arr == null){//问题1、数组要怎么定义arr才等于null? System.out.println("数组定义错误!null值!"); System.exit(0); }else if(length == 0){ System.out.println("数组定义错误!长度等于0!"); System.exit(0); } int minv = Integer.MIN_VALUE; for(int i=0;i<length;i++){ if(arr[i] > minv){ minv = arr[i]; } } return minv; } } 第二题: public static void main(String[] args){ int[] arr = new int[]{1,20,60,90,4,10,20}; System.out.println(Arrays.toString(arr)); int position = getPos(arr,4); System.out.println(position); } public static int getPos(int[] arr,int v){ int num = 0; int position = 0; int length = arr.length; if(arr == null){ System.out.println("数组定义错误!null值!"); System.exit(0); }else if(length == 0){ System.out.println("数组定义错误!长度等于0!"); System.exit(0); } for(int i=0;i<length;i++){ if(v == arr[i]){ num ++; position = i; break; } } return position; } 第三题: public static void main(String[] args){ int[] arr = new int[]{10,20,60,90,4,11,20,2}; int[] bulle_arr = bulleSort(arr); System.out.println(Arrays.toString(bulle_arr)); } //冒泡排序,升序 public static int[] bulleSort(int[] arr){ int length = arr.length; int tmp = 0; for(int i=0;i<length-1;i++){ for(int j=0;j<length-1-i;j++){ if(arr[j]>arr[j+1]){ tmp = arr[j+1]; arr[j+1] = arr[j]; arr[j] = tmp; } } } return arr; } 第四题: public static void main(String[] args){ int[] arr = new int[]{1,2,3,.....,1021,1022,1023}; //log2^1024 = 10; int binv = binSearch(arr,1023); System.out.println(binv); } public static int binSearch(int[] arr,int v){ int length = arr.length; int left = 0; int right = length - 1; int i = 0; int r = 0; int num = 0; while(left <= right){ num ++; i = (left + right)/2; if(arr[i] == v){ r = i; break; }else if(arr[i] > v){ right = i - 1; }else{//arr[i]<v left = i + 1; } if(num >= 1000){ break; } } System.out.println(num); return r; } 第五题:首先是有序,一分为二的去查找,一次去掉一半数据,匹配次数成对数增长。 第六题: public static void main(String[] args){ int[][] arr = {{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}}; for(int i=0;i<arr.length;i++){ System.out.println(Arrays.toString(arr[i])); } int[][] rows_arr = changeArr(arr); for(int i=0;i<rows_arr.length;i++){ System.out.println(Arrays.toString(rows_arr[i])); } } public static int[][] changeArr(int[][] arr){ int tmp = 0; int num = 0; for(int i=0;i<arr.length;i++){ for(int j=i+1;j<arr[i].length;j++){ tmp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = tmp; num ++; } } System.out.println(num); return arr; }
时间: 2024-10-18 23:02:50