冒泡排序:
public static void bubbleSort(int[] arr){for(int i=0;i<arr.length-1;i++){//i<arr,lenth-1表示一共要进行length-1次冒泡,因为最后一次只剩一个未排序元素for (int j=0;j<arr.length-i-1;j++){//j可以理解为arr[j]和arr[j+1]要进行比较,所以小于arr,length—1-iif (arr[j]>arr[j+1]){int temp=arr[j];arr[j]=arr[j+1];arr[j+1]=temp;}}}}
冒泡排序进阶版(有始有终):加强对i和j的理解
public static void bubbleSort(int[] arr,int fromIndex,int toIndex){for (int i=0;i<toIndex-fromIndex-1;i++){for (int j=fromIndex;j<toIndex-1-i;j++){if (arr[j]>arr[j+1]) {int temp=arr[j];arr[j]=arr[j+1];arr[j+1]=temp;}}}}
二分查找:(左闭右开)
public static int binarySearch(int[] arr,int key){int fromIndex=0;int toIndex=arr.length;while(toIndex>fromIndex){int minIndex=fromIndex+(toIndex-fromIndex)/2;if (key==arr[minIndex]){return minIndex;} else if (key<arr[minIndex]){toIndex=minIndex;}else{fromIndex=minIndex+1;}}return -1;}
二分查找(左闭右闭):
public static int binarySearch(int[] arr,int key){int fromIndex=0;int toIndex=arr.length-1;while(toIndex>fromIndex){int minIndex=fromIndex+(toIndex-fromIndex)/2;if (key==arr[minIndex]){return minIndex;} else if (key<arr[minIndex]){toIndex=minIndex-1;}else{fromIndex=minIndex+1;}}return -1;}
Arrays.swap:
public static void swap(int[] arr,int i,int j){int temp=arr[i];arr[i]=arr[j];arr[j]=temp;}
Arrays.fill
public static void fill(int[] arr,int key){for (int i : arr) {arr[i]=key;}}
Arrays.equals
public static boolean equals(int[] arr1,int[] arr2){if (arr1.length!=arr2.length){return false;}else{for (int i=0;i<arr1.length;i++){if (arr1[i]!=arr2[i]){return false;}}return true;}}
Array.copyOf
public static int[] copyOf(int[] original,int length){int newArray[]=new int[length];for (int i=0;i<Math.min(original.length,length);i++){newArray[i]=original[i];}return newArray;}
Arrays.copyOf(有范围):
public static long[] copyRange(long[] original,int fromIndex,int toIndex){long newArray[]=new long[toIndex-fromIndex];for (int i=0;i<Math.min(toIndex,original.length)-fromIndex;i++){newArray[i]=original[fromIndex+i];}return newArray;}