-2

Exercise:

The exercise requires that NO sorting is to be used e.g. descending order. I'm required to find the highest values from the array as is.

Example:

double[] arr = new double[5] {12.1, 5.9, 2.9, 6.8, 20.5}

Ask user for number = 3

I dont know how to do the calculations.

The highest values are

20.5, 12.1, 6.8

From what i understand i need to ask the user for a number. From that number create a way to search the array for the highest decimal number with NO sorting.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
nat1
  • 23
  • 4

4 Answers4

3

OP: How would i code a program that will search a double array for the n amount of highest values. The n is determined by the user. For example a user inputs the number 3, the program is required to display the 3 highest values from the array.

You could use LINQ OrderByDescending to order the array and then use LINQ Take to take the n highest values. I also added int.TryParse(Console.ReadLine(), out n) to check if the user input is really an integer, if not the user is asked again to enter the number of highest elements he wants to extract from the array.

static void Main()
{
    double[] arr = { 2.11, 70.22, 15.67, 92.88, 105.91, 65.32, 40.25, 9.11, 22.09 };

    int n;

    Console.WriteLine("Enter the number of highest elements you want to extract from the array:");

    while(!int.TryParse(Console.ReadLine(), out n))
    {
        Console.WriteLine("Enter the number of highest elements you want to extract from the array:");
    }

    double[] result = arr.OrderByDescending(x=>x).Take(n).ToArray();

    foreach (var item in result)
    {
        Console.WriteLine(item);
    }

    Console.ReadKey();
}

DEMO HERE

result for n=4:

105.91

92.88

70.22

65.32

After the OP Edited the question: From what i understand i need to ask the user for a number. From that number create a way to search the array for the highest decimal number with NO sorting.

Here is a solution without sorting the initial array:

static void Main()
{
    int i,n;
    Console.WriteLine("Enter the number of highest elements you want to extract from the array:");
    while (!int.TryParse(Console.ReadLine(), out n))
    {
        Console.WriteLine("Enter the number of highest elements you want to extract from the array:");
    }
    double[] arr = { 12.1, 5.9, 2.9, 6.8, 20.5 };
    if (n > arr.Length)
        n = arr.Length;
    double[] result = new double[n];
    double max = 0;
    int k;
    for (int j = 0; j < n; j++)
    {
        max = arr[0];
        k = 0;
        for (i = 1; i < arr.Length; i++)
        {
            if (max < arr[i])
            {
                max = arr[i];
                k = i;
            }
        }
        result[j] = max;
        arr[k] = Double.MinValue;

        Console.WriteLine("Highest numbers: {0}", result[j]);
    }
    Console.ReadKey();
}

DEMO HERE

Slaven Tojić
  • 2,945
  • 2
  • 14
  • 33
2

Without sorting the arr array, but using a sorted additional collection containing the highest numbers found at any time:

double[] arr = new double[5] { 12.1, 5.9, 2.9, 6.8, 20.5 };

int num = 3;

var lst = new List<double>();

foreach (double n in arr)
{
    if (lst.Count < num)
    {
        lst.Add(n);
        lst.Sort();
    }
    else if (n >= lst[0])
    {
        lst[0] = n;
        lst.Sort();
    }
}

foreach (double n in lst)
{
    Console.WriteLine(n);
}

Without using any sort, but simply using a find-the-index-of-the-lowest-element function:

static int LowestIndex(double[] dbl)
{
    if (dbl.Length == 0)
    {
        return -1;
    }

    int minIx = 0;

    for (int i = 1; i < dbl.Length; i++)
    {
        if (dbl[i] < dbl[minIx])
        {
            minIx = i;
        }
    }

    return minIx;
}

then

double[] arr = new double[5] { 12.1, 5.9, 2.9, 6.8, 20.5 };

int num = 3;

var lst = new List<double>();
int minIx = -1;

foreach (double n in arr)
{
    if (lst.Count < num)
    {
        lst.Add(n);
        continue;
    }

    if (minIx == -1)
    {
        minIx = LowestIndex(arr);
    }

    if (n >= arr[minIx])
    {
        lst[minIx] = n;
        minIx = -1;
    }
}

foreach (double n in lst)
{
    Console.WriteLine(n);
}

Similar to the previous, but instead of sorting the lst list and considering the element at index [0] to be the lowest, we use a LowestIndex method... Note that to make everything more interesting, I "cache" when possible the LowestIndex result.

Third way, similar to the first one: lst is kept sorted "manually" (so when we add a new element to lst, we add it in the "right" position to keep lst sorted)... Much more complex :-) Note that I'm using List<T>.BinarySearch that has a "very interesting" way of returning the index when no exact match is found.

double[] arr = new double[] { 30, 1, 1, 12.1, 5.9, 2.9, 6.8, 20.5 };

int num = 3;

var lst = new List<double>();

foreach (double n in arr)
{
    int ix = lst.BinarySearch(n);
    if (ix < 0)
    {
        ix = ~ix;
    }

    if (ix == 0 && lst.Count == num)
    {
        continue;
    }

    if (lst.Count == num)
    {
        lst.RemoveAt(0);
        ix--;
    }

    lst.Insert(ix, n);
}

foreach (double n in lst)
{
    Console.WriteLine(n);
}
xanatos
  • 109,618
  • 12
  • 197
  • 280
  • Thanks, but your code went over my head. Is this exercise considered hard? i'm a noob but i hoped i knew a little bit about c# but from your implementation i have a lot to learn. – nat1 May 16 '18 at 07:26
  • @nat1 It isn't C#-hard... it is only "logically" hard. The second way doesn't use any advanced construct or function. – xanatos May 16 '18 at 07:30
  • Cheers for all the examples. – nat1 May 16 '18 at 07:36
  • You gave me different approaches for bubble sort, kudos to you +1 – Prasad Telkikar May 16 '18 at 07:38
  • @xanatos, what are the reasons behind 0 upvotes to my solution, is list not a appropriate data structure to get max from array? or the way is wrong – Prasad Telkikar May 16 '18 at 09:03
  • @Prasadtelkikar Probably luck and formatting :-) I gave you a +1 :-) – xanatos May 16 '18 at 09:09
  • :) is that my luck which stopped people to upvote my answer? I thought my answer is not satisfying or missing any technical aspect. So I asked you a question. (It might be memory leak or something else) Just to learn from you – Prasad Telkikar May 16 '18 at 09:13
  • @Prasadtelkikar Badly formatted code seems "less correct" and "less tidy" than correctly formatted code. From a technical standpoint, duplicating the array in the list and then removing elements from the list seems to be counterintuitive (it is correct, but it doesn't "flow" in the mind of the reader) – xanatos May 16 '18 at 09:15
  • @xanatos, thanks for your suggestions, I formatted my answer. To make it more readable and to understand easily I used List instead of bubble sort. BTW thanks again – Prasad Telkikar May 16 '18 at 09:26
1

OP: a program that will search an unsorted double array ie decimal numbers for the n amount of highest decimal values. The n is determined by the user. For example a user inputs the number 3, the program is required to display the 3 highest decimal values from the array.

By using the LINQ OrderByDescending and Take in such a way:

public static void Main()
{
        double[] array = new double[5] {12.1, 5.9, 2.9, 6.8, 20.5};

        Console.WriteLine("Enter input:");              // Prompt for input
        string input = Console.ReadLine();       

        int totalNums = Convert.ToInt32(input);

        //sort the array in descending order and get 
        //the desired number of elements out of it

        var topNumbers = array.OrderByDescending(i => i) 
                    .Take(totalNums);
        foreach (var x in topNumbers)
        {
            Console.WriteLine(x);
        }
    }

OUTPUT:

enter image description here

dotNetFiddle

DirtyBit
  • 16,613
  • 4
  • 34
  • 55
  • @nat1 indeed, if there is anything you do not understand in the answer above, I would be glad to explain! cheers – DirtyBit May 16 '18 at 06:42
  • Please checkout OP's updated question, he/she don't want to use Sorting.. Check mine as well ;) – Prasad Telkikar May 16 '18 at 07:12
  • 2
    Your solution in one row: `Console.WriteLine(string.Join("\n", array.OrderByDescending(x => x).Take(int.Parse(Console.ReadLine()))));` – HelloWorld May 16 '18 at 07:42
1

You can try with this approach as well

1.Sort your array in descending order.

2.Loop for first n element to get n highest numbers from array.

double[] arr = { 2.1, 70.1, 15.1, 92.1, 105.1, 65.1, 40.1, 9.1, 22.1 };
int n = 3; //This you can take it from user by using Console.ReadLine()
double[] result = arr.OrderByDescending(x=>x).ToArray();
//Result will contais {105, 92, 70, 65, 40, 22, 15, 9, 2}
//More readable to newbie 
Console.WriteLine("Top {0} elements from Array", n);
for(int i = 0; i < n; i++)
    {
      Console.Write(result[i]+" ");
    }

Output:
Top 3 elements from Array
105.1 92.1 70.1

DotNetFiddler


If you don't want to use sorting technique, then you can try with following approach

double[] arr = { 2.1, 70.1, 15.1, 92.1, 105.1, 65.1, 40.1, 9.1, 22.1 };     
int n = 3;
List<double> list = new List<double>(arr);
Console.WriteLine("Top {0} elements", n);
for(int i = 0; i < n; i++)
    {
      double max = list.Max();  
      Console.WriteLine(max);
      list.Remove(max);
    }

Output:Top 3 elements
105.1
92.1
70.1

DotNetFiddler

Do not miss to add System.Linq, System.Collections.Generic namespace.

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44