“Wyszukiwanie binarne Java” Kod odpowiedzi

Wyszukiwanie binarne Java

/*
Java Implementation of Binary Search Algorithm.
- Assuming the Array is Sorted (Ascending Order)
- returns the Index, if Element found.
- -1, if not found.
*/
public class BinarySearch {

    int binarysearch(int[] array, int element) {
        int a_pointer = 0;
        int b_pointer = array.length -1;
      	if (array[a_pointer] == element) return a_pointer;
        if (array[b_pointer] == element) return b_pointer;

        while(a_pointer <= b_pointer){
            int midpoint = a_pointer + (b_pointer - a_pointer) / 2;
          	if (array[midpoint] == element) return midpoint;
          
          	// ignoring the left half, if this is True.
            if (array[midpoint] < element) a_pointer = midpoint + 1;
          
          	// ignoring the right half, if this is True.
            else if (array[midpoint] > element) b_pointer = midpoint - 1;
        }
        return -1;	// Element not Found
    }
    public static void main(String[] args) {
        int[] list = {1, 2, 3, 4, 7, 9, 11, 12, 15, 19, 23, 36, 54, 87};
        System.out.println(binarysearch(list, 19));
    }
}
Prabhu Kiran Konda

Wyszukiwanie Java za pomocą BinarySearch ()

import java.util.Collections;
import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // Creating an ArrayList
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);

        // Using binarySearch()
        int pos = Collections.binarySearch(numbers, 3);
        System.out.println("The position of 3 is " + pos);
    }
}
SAMER SAEID

Poszukiwanie binarne Java

import java.util.*;
public class array
{
    static Scanner sc=new Scanner(System.in);
    public static void main(String[] args)
    {
        System.out.println("Enter the number of elements in the array:");
        int x=sc.nextInt();
        int arr[]=new int[x];
        System.out.println("Enter the sorted elements in the array:");
        for(int i=0; i<arr.length; i++)
        {
            arr[i]=sc.nextInt();
        }
        System.out.println("Enter the element to be searched for in the array:");
        int y=sc.nextInt();
        int max=arr.length-1;
        int min=0;
        int mid;
        while(max>=min)
        {
            mid=(min+max)/2;
            if(y==arr[mid])
            {
                System.out.println("The requested element is at index "+mid);
                break;
            }
            else if(y>arr[mid])
                min=mid+1;
            else if(y<arr[mid])
                max=mid-1;
            if(min>max)
                System.out.println("Requested element is not in the array.");
        }
    }
}
Chaitanya Mishra

Odpowiedzi podobne do “Wyszukiwanie binarne Java”

Przeglądaj popularne odpowiedzi na kod według języka

Przeglądaj inne języki kodu