I'm trying to do a simple sorting of my own (I know Array.Sort()
exists), receiving a user input array and then calling the method sortMyArray()
to sort the numbers from smallest to largest. Which does what intended, except for when I try to find the smallest number of an array that contains 0.
As you will see: I'm initialising the variable smallest
to the value int.MaxValue
at each iteration, but if the array contains a 0, it stays set to to the int.MaxValue
.
static int findSmallest(int[] original, int[] sorted, int smallest)
{
for (int i = 0; i < sorted.Length; i++)
{
if (original[i] < smallest & !sorted.Contains(original[i]))
{
smallest = original[i];
}
}
return smallest;
}
static int[] sortMyArray(int[] original)
{
int[] sorted = new int[original.Length];
for (int i = 0; i < sorted.Length; i++)
{
int smallest = int.MaxValue;
smallest = findSmallest(original, sorted, smallest);
sorted[i] = smallest;
}
return sorted;
}
sortMyArray(inputArray);
My question is, how can I make sure 0 is properly handled?
The code behaves as intended for positive and negative integer values, but what is causing the 0 to not work?
Edit: For example, if the inputArray contains {5, -1, 7, 0, 33}
, then the method will return it sorted as such: {-1, 5, 7, 33, 2147483647}
.
With !sorted.Contains(original[i])
you skip over any value that is already in the array. sorted
is initialized to all 0
's so it will never set smallest = 0
. In your last iteration in sortMyArray
, smallest
will be equal to int.Max
. Note, this will also happen when you have the same element twice. Since you want to implement your own sorting method (and not use Array.Sort
), you should look into various sorting algorithms (i.e. Merge Sort, Quick Sort, etc.) as yours won't work as intended.