【发布时间】:2019-04-24 21:52:56
【问题描述】:
好的,我的选择排序算法有问题。它可以很好地对整数进行排序,但是当我尝试将其用于双打时,它开始随机排序。
这是我的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Sorter.ListSort;
using System.Collections;
namespace ConsoleApp20
{
class Program
{
static void Main(string[] args)
{
var x = new List<double>();
x.Add(23.1);
x.Add(1.5);
x.Add(3);
x.Add(15.23);
x.Add(101.2);
x.Add(23.35);
var sorted = selectionSort(x);
foreach (double s in sorted)
Console.WriteLine(s);
Console.ReadLine();
}
public static List<double> selectionSort(List<double> data)
{
int count = data.Count;
// Console.WriteLine(count);
for (int i = 0; i < count - 1; i++)
{
int min = i;
for (int j = i + 1; j < count; j++)
{
if (data[j] < data[min])
min = j;
double temp = data[min];
data[min] = data[i];
data[i] = temp;
}
}
return data;
}
}
}
现在这是算法返回的内容
【问题讨论】:
-
我认为您应该只在查看整个列表以找到它之后才将最小元素交换到位,而不是每次迭代。
-
明白了,谢谢。有一双额外的眼睛总是很棒!
-
没有理由认为数据类型会有所不同。
标签: c# algorithm sorting selection-sort