删除数组某个元素的普通方法
package cn.zzsxt.test.demo5; public class TestArrayDelete { public static void delete(int[] arr,int element){ int index = -1; System.out.println("删除前的数组为:"); for(int i=0;i<arr.length;i++){ System.out.print(arr[i]+" "); if(element ==arr[i]){ index = i; } } for(int i=index;i<arr.length-1;i++){ arr[i]=arr[i+1]; } System.out.println(); arr[arr.length-1]=0; System.out.println("删除后的数组为:"); for(int n : arr){ System.out.print(n+" "); } } public static void main(String[] args){ int[] nums = {10,20,30,40,50}; delete(nums,50); } }
冒泡排序的底层实现代码
package cn.zzsxt.test.demo5; public class TestSort { public static void printElement(int[] arr){ for(int n : arr){ System.out.print(n+" "); } } public static void sort(int[] arr){ 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; temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } } public static void main(String[] args){ int[] nums = {1,3,5,2,7,4,8,6,9}; System.out.println("排序前:"); printElement(nums); System.out.println(""); sort(nums); System.out.println("排序后:"); printElement(nums); } }
二分法查到(折半查找)的底层实现代码
package cn.zzsxt.test.demo5; public class TestBinarySearch { public static void main(String[] args){ int[] nums = {1,2,4,5,7,8,9}; int index = binarySearch(nums,9); System.out.println(index); } public static int binarySearch(int[] arr,int element){ int left =0; int right = arr.length-1; int middle ; int index = -1; while(left<=right){ middle = (left+right)/2; if(arr[middle]==element){ index = middle; break; }else if(arr[middle]>element){ right = middle-1; }else if(arr[middle]<element){ left = middle+1; } } return index; } }