【发布时间】:2020-07-26 01:20:41
【问题描述】:
我正在尝试使用具有交换方法的已实现数据数组类来使选择排序算法工作。问题是当我尝试运行代码以查看它是否有效时,输出中没有任何变化,我对为什么会这样感到非常困惑。数字是每次随机生成的
public static void SelectionSort(DataArray items)
{
int index = 0;
double minValue = 0;
for(int i = 0; i < items.Length - 1; i++)
{
index = i;
minValue = items[i];
for(int j = i + 1; j < items.Length; j++)
{
if(minValue > items[j])
{
minValue = items[j];
index = j;
}
}
items.Swap(i, index, items[i], minValue);
}
我的交换方法
class MyDataArray:DataArray
{
double[] data;
public MyDataArray(int n, int seed)
{
data = new double[n];
length = n;
Random rand = new Random(seed);
for
(int i = 0; i < length; i++)
{
data[i] = rand.NextDouble();
}
}
public MyDataArray(int n)
{
data = new double[n];
length = n;
}
public override double this[int index]
{
get { return data[index]; }
}
public override void Swap(int i, int j, double a, double b)
{
data[i] = a;
data[j] = b;
}
}
}
数据数组类
abstract class DataArray
{
public int length;
public int Length { get { return length; } }
public abstract double this[int index] { get; }
public abstract void Swap(int i, int j, double a, double b);
public void Print(int n)
{
for (int i = 0; i < n; i++)
Console.Write(" {0:F3} ", this[i]);
Console.WriteLine();
}
}
当我尝试使用这种方法运行代码时
public static void Test_Array_List(int seed)
{
int n = 12;
MyDataArray myarray = new MyDataArray(n, seed);
Console.WriteLine("Before sorting");
myarray.Print(n);
Console.WriteLine("After sorting");
SelectionSort(myarray);
myarray.Print(n);
}
我得到这个结果没有任何变化,我不知道为什么
Before sorting
0.216 0.578 0.831 0.898 0.653 0.496 0.380 0.567 0.230 0.611 0.091 0.076
After sorting
0.216 0.578 0.831 0.898 0.653 0.496 0.380 0.567 0.230 0.611 0.091 0.076
Press any key to continue . .
在此感谢您
【问题讨论】:
标签: c# selection-sort