Почему не работает метод двоичного поиска, если массив отсортирован в порядке убывания? - PullRequest
0 голосов
/ 19 марта 2019

Бинарный метод поиска используется для определения значений из отсортированного массива, который он не выполняет.Я знаю, что проблема заключается в сортировке по убыванию, но это не сработает, если кто-нибудь поможет мне разобраться в проблеме.Нисходящий метод - сортировка выбора, если это помогает.Я думаю, что проблема в том, что метод может найти значение только в массиве по возрастанию, но не знаю, как заставить его работать в массиве по убыванию

package project;

import java.io.*;
import java.util.*;
import java.util.Scanner;

public class project {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int Size;//size of the array
        int order; // ascending or descending order
        System.out.println("Put in the amount of expenses you have");
        Size = sc.nextInt();//User input for the amount of expenses
        System.out.println("put in all your expenses");
        int userInput[] = new int[Size];// what the users expenses are
        for (int i = 0; i < userInput.length; i++)//This loop is for if the i value is smaller than user input then put in more values to complete the array
            userInput[i] = sc.nextInt();
        System.out.println("do you want it ascending or descending order. If you want it in ascending press 1 or if you want descending press 2");
        order = sc.nextInt();// select if they wanted it in ascending or descending order
        System.out.print("expenses not sorted : ");
        printExpenses(userInput);
        if (order == 1) {
            expensesAscending(userInput);// If order is equal to one then sort in ascending else if it is equal to 2 then order it descending
        } else if (order == 2) {
            expensedescending(userInput);

        }
        int ans = binarySearch(userInput, 0, Size, 10);
        System.out.println(ans);
        if(ans == -1)
            System.out.println("Key not found");
          else
            System.out.println("Key found at position " + (ans));
    }

    public static void printExpenses(int[] arr) {
        // this is were it is printed
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i] + "$");
        }
    }

    public static void expensedescending(int arr[]) {
        // This is were the selection sort starts
        int N = arr.length;
        for (int i = 0; i < N; i++) {
            int small = arr[i];
            int pos = i;
            for (int j = i + 1; j < N; j++) {
                if (arr[j] > small) {
                    small = arr[j];
                    pos = j;
                }
            }
            int temp = arr[pos];
            arr[pos] = arr[i];
            arr[i] = temp;
            System.out.println(": ");
            // Printing array after pass
            printExpenses(arr);
        }
    }

    public static void expensesAscending(int arr[]) {
        int N = arr.length;
        for (int i = 1; i < N; i++) {
            int j = i - 1;
            int temp = arr[i];
            while (j >= 0 && temp < arr[j]) {
                arr[j + 1] = arr[j];
                j--;
                ;
            }
            arr[j + 1] = temp;
            System.out.println(": ");
            // Printing array after pass
            printExpenses(arr);
        }
    }
    static int binarySearch(int[] array, int left, int right, int key) {
        if (left > right) {
          return -1;
        }

        int mid = (left + right) / 2;

        if (array[mid] == key) {
          return mid;
        }

        if (array[mid] > key) {
          return binarySearch(array, left, mid - 1, key);
        }

        return binarySearch(array, mid + 1, right, key);
      }



}

Ответы [ 2 ]

1 голос
/ 19 марта 2019

Вы пытаетесь binary search отсортировать массив по возрастанию в отсортированном порядке по убыванию.Измените method header и тело метода следующим образом:

int ans = binarySearch(userInput, 0, Size, 10,order);  // order you got from user 

Теперь этот Binary search будет работать как в порядке возрастания, так и в порядке убывания массива:

    static int binarySearch(int[] array, int left, int right, int key,int sorting) 
    {
        if (left > right) 
        {
          return -1;
        }

        int mid = (left + right) / 2;

        if (array[mid] == key) 
        {
          return mid;
        }

        if(sorting == 2)   // if array is sorted in descending order
        {
            if (array[mid] > key) 
            {
              return binarySearch(array, mid+1, right, key,sorting );
            }
            return binarySearch(array, left, mid-1, key,sorting );
        }
        else // if array is sorted in ascnending order
        {
            if (array[mid] > key) 
            {
                return binarySearch(array, left, mid - 1, key,sorting );
            }

            return binarySearch(array, mid + 1, right, key,sorting );
        }
    }
0 голосов
/ 19 марта 2019

Проблема в том, что вам нужно искать в верхней половине, если ключ меньше, чем средний элемент.Еще поиск в нижней половине.

static int binarySearch(int[] array, int left, int right, int key) {
    if (left > right) {
      return -1;
    }

    int mid = (left + right) / 2;

    if (array[mid] == key) {
      return mid;
    }

    if (array[mid] > key) {
      return binarySearch(array, mid + 1, right, key);
    }

    return binarySearch(array, left, mid - 1, key);
  }
...