public class BinarySearch { /** * @param args */ public static void main(String[] args) { int[] array = {5,13,19,21,37,56,64,75,80,88,92}; System.out.println(BinarySearch.bindarySearch3(array, 0,array.length-1,80)); int i = Arrays.binarySearch(array, 80); System.out.println(i); } /** * @param array[] 有序整型数组 * @param searchkey 要查找的值 * @return 返回searchkey 在array[]中的位置 */ static int bindarySearch(int array[],int searchkey){ int low = 0; int high = array.length - 1; while(low <= high){ int middle = (low + high)/2; if(array[middle] == searchkey){ return middle; }else if(array[middle] > searchkey){ high = middle -1; }else if(array[middle] < searchkey){ low = middle + 1; } } return -1; }//以下是递归实现的,注意边界值。 static int bindarySearch3(int array[],int low,int high,int searchkey){ if(low > high){ return -1; } int middle = (low + high)/2; if(array[middle] == searchkey){ return middle; }else if(array[middle] > searchkey){ high = middle - 1; return bindarySearch3(array,low,high,searchkey); }else if(array[middle] < searchkey){ low = middle + 1 ; return bindarySearch3(array,low,high,searchkey); } return -1; } }
public class QuickSort { /** * @param args */ public static void main(String[] args) { int[] array = {49,38,65,97,76,13,27,51}; System.out.println(partition(array,0,array.length-1)); System.out.println(Arrays.toString(array)); quickSort(array,0,array.length-1); System.out.println(Arrays.toString(array)); } static void quickSort(int[] array,int left,int right){ if(left < right){ int i = partition(array,left,right); quickSort(array,left,i-1); quickSort(array,i+1,right); } } /** * * @param array * @param left * @param right * @return基准记录所在数组的位置 */ static int partition(int[] array,int left ,int right ){ int base = array[left];//基准记录 while(left != right){ while(array[right] >= base && left<right){ right--; } if(left<right){ int temp = array[right]; array[right] = array[left]; array[left] = temp; left+=1; } while(array[left] <= base && left<right){ left++; } if(left<right){ int temp = array[left]; array[left] = array[right]; array[right] = temp; right-=1; } } return left;//or return right; } }