So I'm trying to implement selection sort in C# but the output isn't exactly what I'm expecting, I tried tracing the loops and even brought out the good ol pen and paper but to no avail
using System;
namespace App
{
class Application
{
public static void Main(string[] args)
{
int[] arr = {23,45,76,22,5666,845,11,2};
foreach (int i in sort(arr))
{
Console.WriteLine($"{i}");
}
}
public static int[] sort(int[] arr)
{
int ind = 0;
int minInd = 0;
int jInd = 0;
foreach(int i in arr)
{
int min = i;
minInd = ind;
foreach(int j in arr)
{
if (i == j)
{
}
else
{
if (j < min)
{
min = j;
minInd = jInd;
}
}
jInd++;
}
int temp = i;
arr[ind] = arr[minInd];
arr[minInd] = temp;
ind++;
jInd = 0;
}
return arr;
}
}
}
for some info, minInd is the index of the minimum value, ind is the index of the outer loop iteraion, and jInd is the index for the inner loop itteration, i tried using the built in IndexOf from the array class but that just results in an indexoutofbounds error, could be a problem in the way C# handles array, i normally use java so maybe they handle them in different ways, also I understand that the time complexity of this algorithm is n^2 so why do we still use it.
The output is 45 76 22 5666 845 11 23 2