How do I identify and locate large values in arrays?
array[10]={2,3424,4234,42,234,234,23423,123,342,3}
In this array, how do I find the first five biggest numbers and the position of those numbers? I.e I want the output as
biggest number was 23423 and its position was 7
Like this ^^^ for the five biggest numbers and their positions.
I want c开发者_开发百科ode for this; I am a student.
Is the array guaranteed to have 10 elements? Are they guaranteed to be positive? If so, you can multiply each element by 10 and add the index to it, then sort the array, then take the 5 largest elements; divide by 10 (integer division) to get the original number, and take % 10 to get the original position.
For a more general solution, you could create a struct to hold the value and original index, then sort the array of structs based on value.
Use any basic sorting algorithm.
You just extend search algorithm for the largest number to search for n = 5 largest numbers. If you use binary search, what should be done first with an array? Well, if you answer this question, you'll probably won't need to binary search it at all ;)
From what I understand the array should be immutable since you want to find the positions as well. So if I am correct you shouldn't sort the array, unless you use a new array of size 10, store the sorted array there, and compare and find between the two arrays etc.
If you want to find it without sorting you could do that :
Find the First biggest number and its position Find the Second biggest number (which is smaller from the First biggest number) and its position Find the third biggest number (which is smaller than the Second biggest number) ...
etc....
This can be done and it's not that hard.
精彩评论