この記事は「
個別のアルゴリズムをつつく0−基本選択ソート。主は此処になおれ!」との連動企画ピヨ。詳しい説明はそちらを見てね。
そして、ボクの実装例を見る前に自分で実装を試みよう。
ではさっそく、つまらないものですがどーぞ♪
using System;
class Program
{
static void Main( string[ ] args ) {
int[ ] values = new int[ ] { 0, 3, 5, 6, 2, 8, 7, 9, 1, 4 };
Console.WriteLine( "整列前のデータ " );
for ( int i = 0; i < values.Length; i++ )
Console.Write( values[ i ] + "\t" );
Console.Write( "\n" );
Console.WriteLine( "整列後のデータ" );
values = SortMan.SelectionSort( values );
for ( int i = 0; i < values.Length; i++ )
Console.Write( values[ i ] + "\t" );
Console.Write( "\n" );
Console.Read( );
}
}
class SortMan
{
//要素を昇順に整列する
public static int[ ] SelectionSort( int[ ] values ) {
for ( int sortPoint = 0; sortPoint < values.Length - 1; sortPoint++ )
{
int min = sortPoint;
for ( int index = sortPoint + 1; index < values.Length; index++ )
{
if ( values[ min ] > values[ index ] ) min = index;
}
if ( min != sortPoint )
Exchange( ref values, sortPoint, min );
}
return values;
}
//要素を交換する
private static void Exchange(
ref int[ ] values, int destination, int source )
{
int tmp = values[ destination ];
values[ destination ] = values[ source ];
values[ source ] = tmp;
}
}
これは見ての通り
int型に固定されているからあまりいい実装とは言えないピヨ。型が固定されていないバージョンは、また今度お見せするするピヨ。
それまでの間にこのプログラムを料理しよう。