【问题标题】:Selection Sort C#选择排序 C#
【发布时间】:2016-12-22 08:31:31
【问题描述】:

你们能解释/模拟选择排序算法吗,我往往​​会在值的交换部分迷失方向。谢谢!

代码如下:

int[] ars = new int[4] { 5, 3, 10, 6 };
int min, tempo;
for (int i = 0; i < ars.Length -1; i++)
{
    min = i;
    for(int ii = i + 1; ii < ars.Length; ii++)
    if (ars[ii] < ars[min])
    {
         min = ii;
    }
    tempo = ars[min];
    ars[min] = ars[i];
    ars[i] = tempo;
}

【问题讨论】:

  • 把每一步写在纸上,看看会发生什么
  • 关于选择排序的维基百科页面对这个算法有很好的可视化en.wikipedia.org/wiki/Selection_sort可能对你有帮助。
  • 你也可以看看这个:youtube.com/watch?v=kPRA0W1kECg
  • @Aidin 不,if 块被计为一个语句。所以不需要额外的括号。
  • @Aidin 我宁愿给if 块一个额外的缩进。这样会更清楚。

标签: c# arrays sorting


【解决方案1】:

它将迭代列表并交换与列表其余部分中找到的最低的当前项,但仅当它低于当前项时。


首先,您需要“记住”旧值,然后再复制该值。

// create copy of the previous value
tempo = ars[min];
// overwrite the old value.
ars[min] = ars[i];
// recall the previous value and assign it to the other in the array
ars[i] = tempo;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-15
    • 2017-07-28
    • 2016-02-21
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    相关资源
    最近更新 更多