I want a faster function to find the Nth biggest number of an Int array in C#. This function takes N and Array and returns index of that number.
Here is what i have already. It simply sorts the array and then returns the index of that number. It works perfectly but I'm not sure if this is the fastest way. it seems logical to be an algorithm without complete sorting.
static int myFunction(int[] array, int N){
int[] indexes = new int[array.Length];
for (int i = 0; i < indexes.Length; i++)
indexes[i] = i;
for (int i = 0; i < array.Length; i++)
{
for (int j = i + 1; j < array.Length; j++)
{
if (array[i] < array[j])
{
int m = array[j];
array[j] = array[i];
array[i] = m;
m = indexes[j];
indexes[j] = indexes[i];
indexes[i] = m;
}
}
}
return indexes[N];
}
some results :
myFunction(new int[] { 1, 3, 2, 0, 10 }, 0); //returns 4 (index of 10)
myFunction(new int[] { 1, 3, 2, 0, 10 }, 1); //returns 1 (index of 3)
myFunction(new int[] { 1, 3, 2, 0, 10 }, 2); //returns 2 (index of 2)
Today in a interview, I was told to write a program which will output the nth highest number in the unsorted array, I solved this using javascript, the program is as follows, var fn50 = function(){ var reverseSort = function(myArray,highest){ var x = 0, y = 0, z = 0, temp = 0, totalNum = myArray.
To find the largest element from the array, a simple way is to arrange the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and going on, the last element will be the largest element of the array.
The only way to find the largest value in an unsorted array is to look at every value in the array. Think of it this way.
Randomized quickselect algorithm works in average case complexity O(n). Practically it's very rare to be O(n^2). It uses quicksort's partition function
If your array has a size of a zillion numbers and you need the fifth largest number then you are sorting a lot of numbers that you won't need.
Wouldn't it be faster to keep an ascending sorted sequence of length n (linked list?), and for every element check if it is larger than the first one (which is the smallest in the ascending order
After having scanned your complete array, the first element in your sorted sequence is the one you are looking for.
Most comparisons are only with the first element of your sorted array. You'll have to change the array N-times, one time for the N largest numbers. A change of the array is to remove the first element (the smallest) and find the place where to insert the new element to keep the array sorted
Correction: my statement that the array has to be changed N-time is incorrect. This can be seen most easily when offering an array sorted in ascending order: every compared number will be larger than the smallest in the N-size array, and thus cause a replace
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With