I'm playing around with sorting algorithms. The implementation I have of selection sort is the following:
using System;
namespace Sort
{
class Program
{
static void SelectionSort(int[] arr)
{
int smallestIndex, index, minIndex, temp;
for (index = 0; index < arr.Length - 1; index++)
{
smallestIndex = index;
for (minIndex = index; minIndex < arr.Length; minIndex++)
{
if (arr[minIndex] < arr[smallestIndex])
smallestIndex = minIndex;
temp = arr[smallestIndex];
arr[smallestIndex] = arr[index];
arr[index] = temp;
}
}
}
static void Main(string[] args)
{
int[] myList = {18, 16, 3, 90, 22, 10, 18, 7, 0, 43, 72, 98, 5, 44};
string unsorted = "";
string sorted = "";
// First, display the contents of the unsorted list.
foreach (var item in myList)
{
unsorted = unsorted + item.ToString() + " ";
}
Console.WriteLine("- Original list: " + unsorted);
// Now, sort and display the contents of the list after sorting.
SelectionSort(myList);
foreach (var item in myList)
{
sorted = sorted + item.ToString() + " ";
}
Console.WriteLine("- Sorted list: " + sorted);
Console.WriteLine("- List Size " + myList.Length);
}
}
}
This produces the following output:
- Original list: 18 16 3 90 22 10 18 7 0 43 72 98 5 44
- Sorted list: 7 3 10 16 18 18 22 43 0 44 5 72 90 98
- List Size 14
Which, obviously, isn't quite right. I'm not really sure what's wrong with the implementation I have. How would I fix this?
Just take the swap part out of the loop.