This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace SelectionSort | |
{ | |
public static class Program | |
{ | |
private static int[] SelectionSort(int[] value) | |
{ | |
if (value != null && value.Length > 1) | |
{ | |
for (var targetIndex = 0; targetIndex < value.Length - 1; ++targetIndex) | |
{ | |
var minIndex = targetIndex; | |
for (var index = targetIndex + 1; index < value.Length; ++index) | |
{ | |
if (value[index] < value[minIndex]) | |
{ | |
minIndex = index; | |
} | |
} | |
if (minIndex != targetIndex) // if we found a minimum in the rest of the array, swap | |
{ | |
var tmp = value[minIndex]; | |
value[minIndex] = value[targetIndex]; | |
value[targetIndex] = tmp; | |
} | |
} | |
} | |
return value; | |
} | |
private static void PrintArray(ICollection<int> value) | |
{ | |
if (value != null) | |
{ | |
if (value.Count == 0) | |
{ | |
Console.WriteLine("(Empty Array)"); | |
} | |
else | |
{ | |
Console.WriteLine(string.Join(", ", value.Select(v => v.ToString()).ToArray())); | |
} | |
} | |
else | |
{ | |
Console.WriteLine("(Null Array)"); | |
} | |
} | |
public static int Main() | |
{ | |
PrintArray(SelectionSort(null)); | |
PrintArray(SelectionSort(new int[0])); | |
PrintArray(SelectionSort(new[] { 1 })); | |
PrintArray(SelectionSort(new[] { 4, 3, 2, 1 })); | |
PrintArray(SelectionSort(new[] { 1, 2, 3, 4 })); | |
PrintArray(SelectionSort(new[] { 3, 1, 2, 4 })); | |
PrintArray(SelectionSort(new[] { 2, 4, 1, 3 })); | |
PrintArray(SelectionSort(new[] { 1, 1, 1 })); | |
PrintArray(SelectionSort(new[] { 2, 2, 4, 1, 1, 1, 3 })); | |
return 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment