I’m trying to build a simple program that sorts numbers from biggest to smallest with arrays in c#.
//basic number sorter. every number should be on one line and separated by a " " (space).
int[] numbers = Console.ReadLine().Split(" ").Select(int.Parse).ToArray();
int[] bigToSmall = new int[numbers.Length];
int biggestNum = int.MinValue;
for (int y = 0; y < numbers.Length; y++)
{
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] > biggestNum)
{
biggestNum = numbers[i];
}
else if (numbers[i] == biggestNum)
{
numbers[i] = biggestNum;
}
}
var bigIndx = Array.FindIndex(numbers, row => row == biggestNum);
numbers[bigIndx] = 0;
bigToSmall[y] = biggestNum;
}
for (int i = 0; i < bigToSmall.Length; i++)
{
Console.WriteLine(bigToSmall[i]);
}
When I run the program I get: "Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array."
Here are also the values I get when I use the input "1 2 3"
I have tried to use also IndexOf,but it didnt work. Any ideas why it doesn’t work, and how I can fix it?
>Solution :
It will be the second iteration through the y loop. You haven’t reset biggestNum back to minvalue so it will be looking for the one you removed last time.