1 package com.hanqi;
 2 
 3 import java.util.*;
 4 
 5 public class Test5 {
 6 
 7     public static void main(String[] args) {
 8         // TODO 自动生成的方法存根
 9         //数组的二分查找法
10         //前提:数组要排好序
11         
12         //1.随机生成生成数组
13         Random r1 = new Random();
14         int[] array = new int[10];
15         for (int i = 0; i < array.length; i++) {
16             // 产生随机数
17             array[i] = r1.nextInt(100);
18         }
19         // 遍历输出数组
20         System.out.println("数组的原始顺序");
21         for (int t : array) {
22             System.out.print(t + " ");
23         }
24         
25         //2.冒泡排序
26         System.out.println("排序后的顺序");
27         //总的循环次数
28         for (int k = 0; k < array.length - 1; k++) {
29             //优化:每次冒泡时的循环次数,比上一次少1
30             for (int i = 0; i < array.length - 1-k; i++) {
31                 if (array[i] > array[i + 1]) {
32                     // 从小到大
33                     int zhong = array[i];
34                     array[i] = array[i + 1];
35                     array[i + 1] = zhong;
36 
37                 }
38             }
39             System.out.println("数组第" + (k + 1) + "次排序后的顺序");
40             for (int t : array) {
41                 System.out.print(t + " ");
42             }
43         }
44         //3.二分查找
45         
46         //1)计算出数组的中间位置:(开始位置索引+结束位置索引)/2
47         
48         //2)取出中间未知的值和要查找的数字比较,根据比较结果决定下一步查找的部分
49         //3)计算出下一部分数组的中间位置
50         
51         //要查找的值
52         
53         
54         int a=53;
55         //找到的值得位置
56         
57         int w=-1;//-1代表没找到
58         //开始索引
59         int  start=0;
60         //结束索引
61         int  end=array.length-1;
62         //循环条件
63         while(start<=end)
64         {
65         int m=(start+end)/2;
66         if(a==array[m])
67         {
68             w=m;//找到了
69             break;
70         }
71         else if(a>array[m])
72         {
73             start=m+1;
74         }
75         else
76         {
77             end=m-1;
78         }
79         }
80         System.out.println("找到的位置是"+w);
81     }
82 
83 }

 

 

 

 

posted on 2016-05-13 14:58  周帝  阅读(191)  评论(0编辑  收藏  举报