How to use the Java binary search method
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)