What is the performance of Collections.binarySearch for manually searching a list?

I would like to know which one to use. I have a list of students. I want to find a student with his name. So far, I have done this manually by iterating over the list as shown below.

for(int i = 0; i < list.size(); i++) {
    Student student = list.get(i);
    if(student.getName().equals(studentNameIWantToSearch)) {
        index = i;
        break;
    }
}

Student student = list.get(index);
//my logic from here

I recently saw a method named binarySearch(List<? extends T> list, T key, Comparator<? super T> c)from Collections. I read about it. To perform a binary search, the list must be sorted, and it must be passed to the method binarySearchas an argument.

Now, if I do not want to sort the list? Because I do not need sorting. I see sorting as an extra overhead by my logic.

- , . , O (log n). O (n). . . , , java. , java . .

.

+4
3

, .

, 11 : a, c, d, f, g, j, m, p, r, s, z. for 1- 11 , 5,5 , . r . : ( j). r > j, r , j. , m z. r, .

, , . .

. , . , , , "". , , .

+3

Java Collections.sort() O (n log n). , + O (n log n) + O (log n). O (n).

, . , x , , O (n log n) x O (n), x O (log n), , .

+2
what if I don't want to sort the list?

If it is not sorted, the results are undefined. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found.

, , , binarySearch.

an anyone please tell me why should I use binary search instead of manually searching.

ArrayList, random access - , O (log n).

:

This method runs in log(n) time for a "random access" list (which provides near-constant-time positional access). 

, , randon access ex. LinkedList, O(n)

If the specified list does not implement the RandomAccess interface and is large, this method 
will do an iterator-based binary search that performs O(n) link traversals and O(log n) element
comparisons.
0

Source: https://habr.com/ru/post/1545008/


All Articles