Algorithms 2 / 5: Reverse Selection Sort
It has been a while since I have implemented a sorting algorithm - I should probably have implemented these a little bit earlier than I have done :)
Today I bring you the C sharp version of the selection sort I posted earlier. To mix it up a bit htough this implementation is in reverse.
- Find the largest number in the sequence
- If it is larger than the number at the end of the array, swap them
- Find the next largest number
- If it is larger than the next number along from the end of the array, swap them
- Repeat steps 3 and 4 until all the numbers have been sorted.
Here is the code:
/// <summary>
/// Performs a selection sort on an array of ints.
/// </summary>
/// <param name="array">The array to sort.</param>
static void selection_sort(ref int[] array)
{
int limit = array.Length - 1;
while(limit > 0)
{
//find the index with the maximum value
int max_index = 0; //set the max to the first element in the array
//don't search the first element in the array, we have already done that on the line above
for(int i = limit - 1; i > 0; i--)
{
if(array[i] > array[max_index])
max_index = i;
}
if(array[max_index] > array[limit])
{
//we have found an index with a high value than the current limit
swap_places(ref array, max_index, limit);
}
limit--;
}
}
Full Source Code (pastebin)
Link to binary (MD5: ef5e0f15c9bc181d36b193160e3f8ad9
SHA1: ad49eb97675ca6ec9cc9dfebb63fbe03cfa27534
)
Next up: Insertion sorting.