Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use the Java binary search method

Shulou Source: shulou.com Published: 2022-06-01 06:40:51 10月29日 Update

This article mainly introduces "how to use Java binary search method". In daily operation, I believe many people have doubts about how to use Java binary search method. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about how to use Java binary search method. Next, please follow the editor to study!

Function: ranking

Requirements: return an ordered collection to the front end by points, do not display for 0, and give the current user ranking position

Achieve:

Calculate the set of credits for all users (including the current user)

Filter out 0 and rank them in reverse order. The higher the score, the higher the ranking.

Then find the current user information and determine its position in the collection.

Option 1: List.indexOf (object)

Source code

Public int indexOf (Object o) {if (o = = null) {for (int I = 0; I < size; data +) if (elementdata [I] = = null) return I;} else {for (int I = 0; I < size; idata +) if (o.equals (elementdata [I])) return I } list does not contain return-1 return-1;}

The bottom layer is to traverse to determine that the element is equal to return the element position, and the subscript starts at 0, so the result needs + 1.

Can't the current solution solve the problem?

Yes, logical judgment does not require contains to judge whether it is in the set or not.

Can solve the problem, then where did you find it?

First: the traversal of the bottom layer of indexOf is inefficient if, in extreme cases, 10000 users happen to be the 10000 current users.

Solution binary search Collections.binarySearch

Tuning parameters for algorithms optimization algorithm public static int binarySearch (List)

Tags: User method learning location solution problem element score bottom level efficiency more integral help test practical orderly next subscript no put in Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Docker macOS MariaDB vpn MySQL