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
623and it's original position in array is19, next one will be475with original position21and so on). Second line is sorted array itself.