What is the equivalent “nth_element” function in Java?
I don't want to get a sorted array, just the value of the nth element For example, given an array
a = [20,5,1,-3]
I want to check
nth_element(a,2) = 1
In C, there is a function STD:: nth_ Element can do this Is there an equivalent Java function?
thank you!
resolvent
Solution
You can use arrays to solve this problem, and it will be fast
int[] a = new int[] { 20,-3 }; int[] b = new int[a.length]; // Make room for a copy System.arraycopy(a,b,a.length - 1); // A very fast method for copying arrays Arrays.sort(b); // JDK array sorting,also very fast int second = b[1]; // Get the 2nd element of the sorted array
Test output run this Code:
1
The algorithm assumes that you do not want to sort the original array If you don't mind, you can certainly skip creating a second array and perform array copy
The above is the equivalent "nth_element" function in Java collected by programming house for you. What is it? I hope this article can help you solve what is the equivalent "nth_element" function in Java? Program development problems encountered.
If you think the content of the programming home website is good, you are welcome to recommend the programming home website to programmers and friends.