I face some problems to understand sort example so that i am just wondering if some one give me a hand and explain it to me
Thank you for your assistant
+++++++++++++++++++++++++++++++++++
using System;
class TestSelectionSort;
{
public static void Main( )
{
int[] sortArray = {7, 3, 66, 3, -5, 22, -77, 2};
SelectionSort(sortArray);
foreach (int element in sortArray)
Console.Write(element + "\t");
Console.WriteLine();
}
// Include remaining code here
} // end TestSelectionSort
// sort using the selection sort algorithm
static void SelectionSort(int[] data)
{
int next, indexOfMin;
for (next=0; next
{
indexOfMin = Min(data,next,data.Length-1);
Swap(data, indexOfMin, next);
}
}
// find the smallest element in a specified range
static int Min(int[] data, int start, int end)
{
int minIndex = start;
for (int i = start + 1; i <= end; ++i)
if (data[i] < data[minIndex])
minIndex = i; // found a smaller value
return minIndex;
}
static void Swap(int[] data, int first, int second)
{
int temp;
temp = data[first];
data[first] = data[second];
data[second] = temp;
}
Nony reayPosted Feb 11, 2008, 6:11 PM
Hi Alan
Thank you very much for your explain it is now clear. Thanks mate
AlanPosted Feb 11, 2008, 9:34 AM
The SelectionSort() method works as follows:
1. The smallest item in the array is found (by calling the Min() method) and swapped with the item currently at index 0 in the array (by calling the Swap() method).
2. The smallest item in the remainder of the array (from index 1 onwards) is found and swapped with the item currently at index 1.
3. Simlar steps are taken until the penultimate element in the array is reached (at index data.Length - 2]). After this has been swapped, the final element in the array (at index data.Length - 1) must contain the largest element and so you have now sorted the whole array into increasing numerical order.