冒泡排序,二分法查找

	//冒泡排序:左边开始,两数比较,左边大就换位置,每次循环最大的数字到最右边
	public static void bubbleSort(int arr[]) {
		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]){
					int temp =arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
	}
	//二分法查找:low最大索引,high最小索引,mid最大最小和除2,每次比较目标元素与mid索引处的值是否相等,不相等,如果目标元素大就将low=mid+1再次比较,直到low比high小(说明全部比较完成)
	public static int binarySearch(int arr[],int target){
		int low = 0;
		int high = arr.length-1;
		int mid;
		while (low<=high) {
			mid = (low + high) / 2;
			if (target == arr[mid]) {
				return mid + 1;
			} else if (target < arr[mid]) {
				high = mid - 1;
			} else {
				low = mid + 1;
			}
		}
		return -1;
	}


	public static void main(String[] args) {
    	int[] arrInt = {6512,12,5,122,11,51,2,4,512,225,125,1};
    	//先用冒牌排序
		bubbleSort(arrInt);
		//再用二分法查找是否有225这个元素
		int i = binarySearch(arrInt, 225);
		System.out.println(Arrays.toString(arrInt));
		System.out.println(i);
	}

你可能感兴趣的:(Java)