Java例题练习

it2022-05-05  200

//给定一个长度用默认值填充原数组(如果原数组长度小于newLength用默认值填充,如果原数组长度大于原数组长度则截取) public static int[] copyof(int[] original,int newLength) { int[] dest=new int[newLength]; int length=original.length<=newlength?original.length:newLength; for(int i=0;i<length;i++) { dest[i]=original[i]; } return dest; } public static void main(String[] args) { int[] a={1,2,3,4,5}; copy(a,10); System.out.println(); } //二分查找(前提是数组是有序的) public static int binarySearch(int[] a,int v) { int right=a.length;//right=a.length==>[left,right) right=a.lenght-1==>[left,right] int left=0; while(left<right) { int mid=left+(left+right)/2; if(a[mid]>v) right=mid; else if(mid<v) left=mid+1; else return mid; } return -1; } public statuc int binarySearch2(int[] a,int v) { int right=a.lenght-1;//[left,right] int left=0; while(left<=right) { int mid=(left+right)/2; if(a[mid]==v) return mid; else if(a[mid]<v) { left=mid+1; }else if(a[mid]>v) right=mid-1; } return -1; } public static void main(String[] args) { int a[]={1,2,3,4,5}; binarySearch(a,3); System.out.println(); }

最新回复(0)