0
How do you find the kth smallest element in an array without sorting????!!
3 ответов
+ 3
algorithm /ˈalɡərɪð(ə)m/
"a process or set of rules to be followed in calculations or other problem-solving operations, especially by a computer."
(Source: Google/Oxford Languages)
"Without algorithm" - Do you mean that you want to solve this problem without writing any code?
Hmmm maybe with magic?
+ 2
Ok I see you changed the description.
Now we can think about this together. Assuming we have an array of int, the array might also contain duplicate elements, for example {1, 1, 2, 2, 3} in this array, is the second smallest element 1 or 2?
If we assume no duplication, then we can split the problem in two steps:
1. how to find the minimum.
One example algo:
- create a variable for the assumed minimum, set it to the first element of the array.
- loop through the array starting from the second element, and if the current value is smaller than the assumed minimum, replace the min variable
2. how to find the kth smallest element
You'll need to wrap the 'find minimum' algo in another loop that runs k times. Assume k>0.
You need to set another variable as the "global minimum", initially it can be null, after running the inner loop this variable will take the result of minimum.
Inside the inner loop you have to add also a condition to compare the current loop value to this global minimum.
+ 1
You can use Array stream
https://code.sololearn.com/ckK0m9aKrl1T/?ref=app
Or use for loop and compare all values to get the min