简体   繁体   English

为什么我的二进制搜索不返回目标值索引

[英]Why isn't my binary search returning the targeted value Index

I'm working on a coding problem that wants me to use a binary search method to see if a value by the user matches the value in the array that I extracted from a file. 我正在处理一个编码问题,希望我使用二进制搜索方法来查看用户的值是否与从文件中提取的数组中的值匹配。 My binary search however only recognizes the first number inside the array as the target. 但是,我的二进制搜索仅将数组内的第一个数字识别为目标。

I've been wracking my brain for a few hours now and I don't know what's wrong. 我已经动了好几个小时了,我不知道怎么了。

public static void main(String[] args) throws FileNotFoundException {
    final double THRESHOLD = 0.01; //set threshold for doubles comparison
    boolean done = false;
    File fileName;
    Scanner in = new Scanner (System.in);
    Scanner user;
    //prompt user to input a file
    while (!done) {
        System.out.print("Enter the name of the file with your investments: ");
        fileName = new File(in.nextLine());
        user = new Scanner (fileName);
        int size = user.nextInt();
        double investments [] = new double [size];
        int index = 0;
        while (user.hasNextDouble()) {
            investments [index] = user.nextDouble(); 
            index++;
        }
        //sort values into specified categories
        int i = 0, aValues = 0, bValues = 0, cValues = 0, dValues = 0, fValues = 0;
        while (i < investments.length) {
            if (investments [i] > 1250) {
                aValues++;
            }
            if (investments [i] > 1100 && investments [i] < 1500) {
                bValues++;
            }
            if (investments [i] > 900 && investments [i] < 1100) {
                cValues++;
            }
            if (investments [i] > 750 && investments [i] < 900) {
                dValues++;
            }
            if (investments [i] > 0 && investments [i] < 750) {
                fValues++;
            }
        i++;
        }
        //print table
        System.out.printf("\n%-10s$%.2f", "Mean: ", getMean(investments));
        System.out.printf("\n%-10s$%.2f", "Minimum", getMinimum(investments));
        System.out.printf("\n%-10s$%.2f\n", "Maximum", getMaximum(investments));
        System.out.printf("\n%-10s", "Number of As: " + aValues);
        System.out.printf("\n%-10s", "Number of Bs: " + bValues);
        System.out.printf("\n%-10s", "Number of Cs: " + cValues);
        System.out.printf("\n%-10s", "Number of Ds: " + dValues);
        System.out.printf("\n%-10s\n", "Number of Fs: " + fValues);
        System.out.printf("\n%-10s", "Total number of investments: " + size);
        System.out.printf("\n\n");
        //sort array of investments and print
        bubbleSort (investments);
        for (double nvestments : investments) {
            System.out.printf("%.3f\n", nvestments);
        }
        System.out.print("Would you like to search for an investment amount? (Y/N): ");
        String response = in.next();
        do {
        if (response.equalsIgnoreCase("y")) {

            System.out.print("Enter investment amount: $");
            double enteredTarget =  in.nextDouble();
            if (THRESHOLD >= Math.abs(investments[binarySearch(investments, enteredTarget)] - enteredTarget)) {
                done = false;
                System.out.println(investments[binarySearch(investments, enteredTarget)] + "       " + enteredTarget);
                System.out.printf("Investment amount $%.2f is found at position %d\n", enteredTarget, index(investments, enteredTarget)+1);
                System.out.print("Would you like to search for an investment amount? (Y/N): ");
                response = in.next();
            }
            else {
                System.out.println(investments[binarySearch(investments, enteredTarget)] + "       " + enteredTarget);
                System.out.printf("Investment amount $%.2f is found at position 00\n", enteredTarget);
                System.out.print("Would you like to search for an investment amount? (Y/N): ");
                response = in.next();
            }}
            else if (response.equalsIgnoreCase("n")) {
                done = true;
            }
        } while (response.equalsIgnoreCase("y"));
    }
in.close();
}
public static double getMinimum (double [] array) {
    double minValue = array [0];
    for (int i=1; i<array.length; i++) {
        if (array [i] < minValue) {
            minValue = array[i];
        }
    }
    return minValue;
}
public static double getMaximum (double [] array) {
    double maxValue = array [0];
    for (int i=1; i<array.length; i++) {
        if (array [i] > maxValue) {
            maxValue = array[i];
        }
    }
    return maxValue;
}
public static double getMean (double [] array) {
    double sum = 0;
    for (int i = 0; i < array.length; i++) {
        sum = array [i] + sum;
    }
    double mean = sum / array.length;
    return mean;
}
public static void bubbleSort (double [] array) {
    boolean sorted = false;
    int i = 0, j = 0;
    while (!sorted) {
        if (i == array.length) {
            sorted = false;
        }
        else {
            sorted = true;
            for (i = 0; i < array.length-1; i++) {
                for (j = 0; j < array.length-i-1; j++) {
                    if (array [j] < array [j+1]) {
                        swap (array, j, j+1);
                    }
                }
            }
        }
    }
}
public static void swap (double [] array, int j, int i) {
    double temp = array [i];
    array [i] = array [j];
    array [j] = temp;
}
public static int binarySearch (double [] array, double target) {
    int lb = 0;
    int ub = array.length - 1;
    int retVal = -1;
    while (ub >= lb && retVal < 0) {
        int mid = (ub + lb) / 2;
        if (array [mid] < target) {
            lb = mid + 1;
        }
        else if (array [mid] > target) {
            ub = mid - 1;
        }
        else {
            retVal = mid;
        }
    }
return retVal;
}
public static int index (double [] array, double target) {
    int i;
    final double THRESHOLD = 0.01;
    for (i = 0; i < array.length; i++) {
        if (Math.abs(array [i] - target) < THRESHOLD) {
            return i;
        }
    }
return i+1;
}

} }

For instance, if my array contains 800.9, 300, 100, 60.50, 23.45, & 23.33 and I type 100 when it asks me to enter a value, it compares it to 800.9 and not the rest of the values. 例如,如果我的数组包含800.9、300、100、60.50、23.45和23.33,并且当我要求输入一个值时我键入100,它会将其与800.9而不是其余值进行比较。

Binary Search only works on Sorted Arrays and in your case your array is sorted in Descending order and you implement a Binary Search algorithem for Ascending order . Binary Search仅适用于Sorted Array,并且在您的情况下,您的数组以Descending顺序排序,并且您实现了Ascending orderBinary Search算法。

Your Array : 800.9, 300, 100, 60.50, 23.45, & 23.33 // Descending order 您的数组: 800.9, 300, 100, 60.50, 23.45, & 23.33 //降序

For Descending order Array you have to inverse your conditional operators. 对于降序数组,您必须对条件运算符求逆。

if (array [mid] > target) {
    lb = mid + 1;
}
else if (array [mid] < target) {
    ub = mid - 1;
}
else {
    retVal = mid;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM