欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

线性查找与二分查找

程序员文章站 2022-03-14 23:49:02
...
package com.yao.exer;
/*
 * 数组复制反转遍历
 * 线性查找
 * 二分查找
 */
public class ArrayExer6 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String[] arr = new String[] {"JJ","DD","BB","AA","PP","QQ"};
		//数	组的复制
		String[] arr1 = new String[arr.length];
		for(int i = 0;i < arr.length;i++) {
			arr1[i] = arr[i];
		}
		//数组的反转
		//方式一
		for(int i = 0;i < arr.length/2;i++) {
			String temp = arr[i];
			arr[i] = arr[arr.length-i-1];
			arr[arr.length-i-1] = temp;
		}
		//方式二
//		for(int i = 0,j = arr.length-1;i < j;i++,j--) {
//			String temp = arr[i];
//			arr[i] = arr[j];
//			arr[j] = temp;
//		}
		//遍历arr
		for(int i = 0;i<arr.length;i++) {
			System.out.print(arr[i]+"\t");
		}
		System.out.println();
		//线性查找
		String dest = "CC";
		boolean flag = true;
		for(int i = 0;i < arr.length;i++) {
			if(dest.equals(arr[i])) {
				System.out.println("找到了指定的元素,位置为"+i);
				flag = false;
				break;
			}
		}
		if(flag == true) {
			System.out.println("很遗憾没找到");
		}
		//二分法查找:前提是数组必须有序
		int[] arr2 = new int[] {-98,-43,-2,0,2,7,12,36,78,99,143,324};
		int desk1 = 78;
		int head = 0;//初始首索引
		int end = arr2.length - 1;//初始末索引
		flag = true; 
		while(head<=end) {
			int middle = (head + end)/2;
			if(desk1 == arr2[middle]) {
				System.out.println("找到了指定的元素,位置为:" + middle);
				flag = false;
				break;
			}
			else if(arr2[middle] > desk1) {
				end = middle - 1;
			}
			else if(arr2[middle] < desk1) {
				head = middle + 1;
			}
		}
		if(flag == true) {
			System.out.println("很遗憾没找到");
		}
		

	}

}


相关标签: java习题 java