java常用算法
1
package pack; public class Demo { public static void main(String[] args) { int[] arr = {321,22,32,4,52,1}; int temp; arr = maopao(arr);//冒泡排序 for (int i : arr) { System.out.print(i + ","); } int index = zheban2(arr, 32); System.out.println("32的位置是:"+index); } //折半查找 public static int zheban(int[] arr,int key){ int max,min,mid; max=arr.length-1; min=0; mid=(max+min)/2; while(arr[mid]!=key){ if(key>arr[mid]){ min=mid+1; //当key比max还大的时候,算到最后,min=max+1 }else if(key<arr[mid]){ max=mid-1; } if(min>max){ //这里要单独判断 return -1; } mid=(max+min)/2; } return mid; } //折半查找2 public static int zheban2(int []arr,int key){ int min,mid,max; max=arr.length-1; min=0; while(min<=max){ //这里注意是<= mid = (min+max)/2; if(key>arr[mid]){ min=mid+1; }else if(key<arr[mid]){ max=mid-1; }else{ return mid; } } return -1; } //冒泡排序 public static int[] maopao(int[] arr){ int temp; for(int i=0;i<arr.length-1;i++){ for(int j=0;j<arr.length-i-1;j++){ if(arr[j]>arr[j+1]){ temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } return arr; } //选择排序 public static int[] xuanze(int[] arr){ int temp; for(int i=0;i<arr.length-1;i++){ for(int j=i+1;j<arr.length;j++){ if(arr[i]>arr[j]){ temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } return arr; } }