1
\$\begingroup\$

The program sorts the array from lowest to highest and outputs the index of the searched value:

public static void main(String[] args) {
 Integer[] random = {6, -4, 12, 0, -10};
 List<Integer> list = new ArrayList<Integer>(Arrays.asList(random));
 Collections.sort(list);
 Integer[] array = list.toArray(new Integer[list.size()]);
 int y = Arrays.binarySearch(array, 6);
 System.out.println(y);
}

This works as expected, but you can see that I had to use 3 lines just to sort the array, before being able to do a binarySearch on it.

Can this code be improved?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jul 5, 2015 at 12:35
\$\endgroup\$

2 Answers 2

11
\$\begingroup\$

As you say, this is wrong. This

Integer[] random = {6, -4, 12, 0, -10};
List<Integer> list = new ArrayList<Integer>(Arrays.asList(random));
Collections.sort(list);
Integer[] array = list.toArray(new Integer[list.size()]);

could be replaced by

Integer[] random = {6, -4, 12, 0, -10};
List<Integer> list = Arrays.asList(random);
Collections.sort(random);

where Arrays.asList just wraps the array without making a copy. Even better would be

Integer[] random = {6, -4, 12, 0, -10};
Arrays.sort(random);

Also note that sorting something just in order to be able to use binary search once makes no sense.

Also note that

Integer[] random = {6, -4, 12, 0, -10};

uses objects wrapping the int, while

int[] random = {6, -4, 12, 0, -10};

would be much more efficient.

answered Jul 5, 2015 at 12:45
\$\endgroup\$
2
\$\begingroup\$

Boxing the ints and creating a List are both superfluous. You can just sort an array of ints.

int[] array = {6, -4, 12, 0, -10};
Arrays.sort(array);
System.out.println(Arrays.binarySearch(array, 6));

If your goal is to obtain the approximate rank of an element, it would be faster just to count the elements that are smaller.

answered Jul 5, 2015 at 15:54
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.