Гидеон Теон Гидеон Теон - 1 month ago 12
C# Question

get index of array element with duplicate value before sorting

I have array of integers with repeating values. I need to sort it in decreasing order and print 2 lines.

Algorythm:


  • index = 0;

  • Find largest value in array

  • Print out its original index via
    Console.Write($"{maxPos} ");

  • Switch it with element with first value with
    index

  • Repeat for all other elements in array

  • Print out sorted array using
    Console.Write($"{a[i]} ");)



Trouble is I can't get the index printed in console no mater what.

using System;

public class SortProblem
{
public static void Main()
{
Sort();
}

public static void Sort()
{
var array = new []
{
10, 10, 5, 2, 2, 5, 6, 7, 8, 15, 4, 4, 4, 2, 3, 5, 5, 36, 32, 623, 7, 475, 7, 2, 2, 44, 5, 6, 7, 71, 2
};

for (int index = 0; index < array.Length -1; index++)
{
int max = index;

for (int elemIndex = index+1; elemIndex < array.Length; elemIndex++)
{
if (array[elemIndex] > array[max])
{
max = elemIndex;
}
}

int tmp = array[index];
array[index] = array[max];
array[max] = tmp;
}

foreach (int element in array)
{
Console.Write (element+" ");
}
}
}


Expected output is:


19 21 29 25 17 18 9 19 21 21 19 20 22 28 21 27 16 18 26 27 29 22 27 29 27 25 26 27 28 29 30
623 475 71 44 36 32 15 10 10 8 7 7 7 7 6 6 5 5 5 5 5 4 4 4 3 2 2 2 2 2 2

Answer

The simplest solution:

using System;
using System.Linq;

public class SortProblem
{
    public static void Main()
    {
        var result = new[]
        {
            10, 10, 5, 2, 2, 5, 6, 7, 8, 15, 4, 4, 4, 2, 3, 5, 5, 36, 32, 623, 7, 475, 7, 2, 2, 44, 5, 6, 7, 71, 2
        }.Select((element, idx) => new { Value = element, OriginalIndex = idx }).OrderByDescending(item => item.Value).ToList(); // The last one only needed to persist the result set and avoid double processing

        Console.WriteLine(string.Join(" ", result.Select(item => item.OriginalIndex)));
        Console.WriteLine(string.Join(" ", result.Select(item => item.Value)));
    }
}

But to refer back to your algorithm:

using System;
using System.Text;

public class SortProblem
{
    public static void Main()
    {
        Sort();
    }

    private static void Sort()
    {
        StringBuilder sb = new StringBuilder(); 

        var array = new[]
        {
            10, 10, 5, 2, 2, 5, 6, 7, 8, 15, 4, 4, 4, 2, 3, 5, 5, 36, 32, 623, 7, 475, 7, 2, 2, 44, 5, 6, 7, 71, 2
        };

        for (int i = 0; i < array.Length; ++i)
        {
            int max = i;

            for (int j = i + 1; j < array.Length; ++j)
                if (array[max] < array[j])
                    max = j;

            sb.Append(max);
            sb.Append(" ");

            int temp = array[i];
            array[i] = array[max];
            array[max] = temp;
        }

        Console.WriteLine(sb.Remove(sb.Length - 1, 1).ToString());
        Console.WriteLine(string.Join(" ", array));
    }
}