Skip to content

Instantly share code, notes, and snippets.

@milang
Created May 26, 2010 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milang/414942 to your computer and use it in GitHub Desktop.
Save milang/414942 to your computer and use it in GitHub Desktop.
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