二进制搜索数组

时间:2015-03-27 13:47:07

标签: java search binary

此代码使用中位数搜索数组中的数字。我在打印它在阵列中的位置时遇到问题。此代码打印出数组的最大值。前" 234" "你的号码在99999" " 345" "你的号码在99998"等等。

import java.util.Scanner;
import java.util.Arrays;
public class sok2 {

public static void main(String[] args) {

int ListaLength = 100001; //Säger hur lång listan ska vara.
int [] array = new int[ListaLength];
for (int i = 0; i < ListaLength; i++) {
    array[i] = (int)(Math.random() * ((ListaLength - 1) + 1));
    Arrays.sort(array);
    System.out.println("Skriv in numret du letar efter.");
    int element = new Scanner(System.in).nextInt(); 

    boolean found = false;
    int min = 0;
    int max = array.length - 1;
    int median = max/2;

    while(! found && min <= max){
        if(array[median] == element){
            found = true;
        }
        if(array[median] < element){
            min = median + 1;
            median = (min + max) / 2;
        }
        else if(array[median] > element){
            max = median - 1;
            median = (max + min) / 2;
        }
    }
    // this is where i assume the problem is.
    System.out.println("Din siffra är på plats "+median);
}}}

3 个答案:

答案 0 :(得分:0)

每次执行for循环时,你基本上都打印出中位数,如果你想要最后一个位置,保存中位数并在for循环结束时将其打印出来。

答案 1 :(得分:0)

试试这段代码:

public static int bianarySearch(int[] array, int low, int high, int item) {
    int middle = (low + high) / 2;
    if (low > high) {
        return -1;
    } else if (array[mid] == item) {
        return middle;
    } else if (array[mid] < item) {
        return bianarySearch(array, item, middle + 1, high);
    } else {
        return bianarySearch(array, item, low, middle - 1);
    }
}

答案 2 :(得分:0)

对不起,我注意到了我的错误。

int ListaLength = 100001;
int [] array = new int[ListaLength];
for (int i = 0; i < ListaLength; i++) {
array[i] = (int)(Math.random() * ((ListaLength - 1) + 1));
 //there is supposed to be a closing bracket here.
Arrays.sort(array);
System.out.println("Skriv in numret du letar efter.");
int element = new Scanner(System.in).nextInt();