
This a snippet to perform a selection sort on an array. Though it was originally written for a console application it can easily be ported to a Windows application
/// <summary>
/// method to perform a selection sort on an array
/// </summary>
public static void SelectionSort()
{
//variable to hold the array size
int[] arrayNum = new int[100];
int minNum;
bool isNum = false;
int sizeNum;
//ask the user for the size of the array
Console.WriteLine("Number of elements in the array ?");
//read in the value
string sizeString = Console.ReadLine();
isNum = Int32.TryParse(sizeString, out sizeNum);
//now check for a numeric value
if(isNum)
{
//ask the user for the array values
Console.WriteLine("-----------------------");
Console.WriteLine("Enter array values (numeric).");
Console.WriteLine("-----------------------");
//now we loop to the size of the array
for (int i = 0; i < sizeNum; i++)
{
//temp value for the loop
int temp;
//read in the users value
string arrayValue = Console.ReadLine();
//use TryParse to convert to number
isNum = Int32.TryParse(arrayValue, out temp);
//now make sure it's numeric
if (isNum)
{
arrayNum[i] = temp;
}
else
{
Console.WriteLine("Array values must be numeric!");
break;
}
}
//start a 2nd loop for the size of the array
for (int j = 0; j < sizeNum - 1; j++)
{
//assign value to value of the incrementer
minNum = j;
//start a 3rd loop
for (int k = j + 1; k < sizeNum; k++)
{
//check this index of the array to see if it's larger
//that the index of the second loop
if (arrayNum[minNum] > arrayNum[k])
{
minNum = k;
}
}
//now see if the minNum isnt equal to the index of the 3rd loop
if (minNum != j)
{
//now we start the sorting
int finalNum = arrayNum[j];
arrayNum[j] = arrayNum[minNum];
arrayNum[minNum] = finalNum;
}
}
//write out the sorted value of the initial array
Console.WriteLine("--------------------------------------------");
Console.WriteLine("Selection Sort results: ");
//now a final loop to retrieve the items in the sorted value
for (int l = 0; l < sizeNum; l++)
{
Console.WriteLine(arrayNum[l]);
}
}
else
{
Console.WriteLine("The array size must be numeric!");
}
}-Offline- |