【发布时间】:2016-05-28 14:23:28
【问题描述】:
我在玩排序算法。我对选择排序的实现如下:
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);
}
}
}
这会产生以下输出:
- 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
显然,这不太正确。我不太确定我的实现有什么问题。我将如何解决这个问题?
【问题讨论】:
-
如果我错了,请原谅我,因为我有一段时间没有完成排序算法,但是如果我不得不猜测您将数组中的元素运行了固定次数。在不进行任何更改之前,您是否不必继续运行它?
-
太宽泛了...调试。单步执行代码。添加单元测试。从实际的角度来看 - 删除所有并使用
OrderBy或任何其他内置排序。
标签: c# sorting selection-sort