Home  >  Article  >  Java  >  Java program to search user defined object from list by using binary search comparator

Java program to search user defined object from list by using binary search comparator

WBOY
WBOYforward
2023-08-28 16:05:091288browse

Java program to search user defined object from list by using binary search comparator

Java comparator interface for sorting Java objects. Comparator classes in Java compare different objects (Obj 01, Obj 02) by calling "java.util.comparator". In this method, objects can be compared based on the return value. The comparison can be positive, equal, or negative.

This process provides the user with multiple sorting sequences. There are many ways to compare the two methods.

  • public int compare class (obj 1, obj 2) - Performs a comparison between two objects.

  • public Boolean equals (obj) - Compares the current object with the specified object.

Java Collection Class - Provides static methods for sorting elements in a data collection. This collection element is used in TreeMap.

Let us discuss how to build a Java code using comparators to search for a user-defined object from a list via binary search.

Binary search parameters and their components

  • parameter

    • is a specific array

    • fromindex - the first element to search for

    • toindex - the last element to search for key - the value to search for Key-value pairs to be searched

    • Comparators

  • return

    • Returns the index of the search key that exists within the specified range.

  • exception

    • ClassCast

    • Illegal parameter

    • ArrayIndexOutOfBounds

algorithm

  • Step one - start.

  • Step 2 - Intermediate element set calculation.

  • Step 3 - Compare the keyword to the middle element.

  • Step 4 - If the values ​​of key and mid elements are the same; then return the result.

  • Step 5 - Otherwise, the value of the key is greater than the middle element, then follow the right half of the collection

  • Step 6 - Or; if the value of key is less than the mid element then follow upper

Binary search using comparator - syntax

public static int binarySearch(primitive() p,Primitive key)
public static int binarySearch(Object() o,Object key)

public static int binarySearch(Object() o,Object key,Comparator c)
Java Collections binarySearch(List<? extends Comparable1<? super R>> list, R key)and;
Java Collections binarySearch(List<? extends R> list, R key, Comparator<? super R> c)

There are two well-known syntaxes to search for user-defined objects from lists via binary search using comparators. For the first case, the list needs to be sorted in ascending order and the procedure is called using a specific method, where the result is undefined.

On the other hand, to search for a specified object, it is important to call the method.

Following method

  • Method 1 to search for a user-defined object from a list by using a binary searcher and comparator

Search for user-defined objects from a list using a comparator

In these examples, we use collections, binarySearch() and comparator class operations to sort some user-defined data using the binary search operation through the comparator

Example 1: Use Collections, binarySearch() to find data from a list

import java.util.*;

public class Binarysearch {
   public static void main(String[] args){
      List<Domain> l1 = new ArrayList<Domain>();
      l1.add(new Domain(100, "India"));
      l1.add(new Domain(200, "Bangladesh"));
      l1.add(new Domain(300, "Dhaka"));
      l1.add(new Domain(400, "Kolkata"));

      Comparator<Domain> c = new Comparator<Domain>() {
      	 public int compare(Domain u1, Domain u2) {
            return u1.getId().compareTo(u2.getId());
      	 }
      };
      int index = Collections.binarySearch(	l1, new Domain(10, null), c);
      System.out.println("Found at index number zone" + index);
      index = Collections.binarySearch(l1, new Domain(6, null), c);
      System.out.println(index);
   }
}
class Domain {
   private int id;
   private String url;
   public Domain(int id, String url){
      this.id = id;
      this.url = url;
   }
   public Integer getId() { return Integer.valueOf(id); }
}

Output

Found at index number zone-1
-1

Example 2: Sort the list in ascending order

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

public class ascendingsearch {
	public static void main(String[] args){
      List<Integer> ak = new ArrayList<integer>();
      ak.add(100);
      ak.add(200);
      ak.add(30);
      ak.add(10);
      ak.add(20);

      int index = Collections.binarySearch(ak, 100);
      System.out.println(index);
      index = Collections.binarySearch(ak, 130);
      System.out.println(index);
	}
}
</integer>

Output

Note: ascendingsearch.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
-6
-6

Example 3: Sort the list in descending order and find the index number

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

public class binsearchdecend {
	public static void main(String[] args){
      List<Integer> a0710 = new ArrayList<Integer>();
      a0710.add(1000);
      a0710.add(500);
      a0710.add(300);
      a0710.add(10);
      a0710.add(2);
      int index = Collections.binarySearch(
      	a0710, 50, Collections.reverseOrder());

      System.out.println("Found at index number present " + index);
	}
}

Output

Found at index number present -4

Example 4: Find the number of elements and values

import java.util.Scanner;
public class BinarySearchExample{
   public static void main(String args[]){
      int counter, num, item, array[], first, last, middle;
      Scanner input = new Scanner(System.in);
      System.out.println("Enter number of elements:");
      num = input.nextInt(); 
      array = new int[num];

      System.out.println("Enter " + num + " integers");
      for (counter = 0; counter < num; counter++)
          array[counter] = input.nextInt();

      System.out.println("Enter the search value:");
      item = input.nextInt();
      first = 0;
      last = num - 1;
      middle = (first + last)/2;

      while( first <= last ){
         if ( array[middle] < item )
           first = middle + 1;
         else if ( array[middle] == item ){
           System.out.println(item + " found at location " + (middle + 1) + ".");
           break;
         }
         else{
             last = middle - 1;
         }
         middle = (first + last)/2;
      }
      if ( first > last )
         System.out.println(item + " is not found.\n");
   }
}

Output

Enter number of elements:
7
Enter 7 integers
10
12
56
42
48
99
100
Enter the search value:
50
50 is not found.

in conclusion

In this article, we learned about the Comparable interface in Java through some sample codes and algorithms. Here we declare some user-defined classes and comparator interfaces. They serve some specific purposes and allow specific data to be processed in a Java environment.

The above is the detailed content of Java program to search user defined object from list by using binary search comparator. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete