【问题标题】:why does selection sort method start loop with "i = from + 1"为什么选择排序方法以“i = from + 1”开始循环
【发布时间】:2016-10-25 01:48:44
【问题描述】:

我正在使用选择短方法对数组进行排序。该方法以一个以“i = from + 1”开头的 for 循环开始其 minimumPosition 方法。为什么它以那个开头而不是“i = 0”?

谁能帮我解释一下?

谢谢!

编辑:添加上下文

/**
 Finds the smallest element in a tail range of the array.
 @param a the array to sort
@param from the first position in a to compare
@return the position of the smallest element in the
 range a[from] . . . a[a.length - 1]
*/
private static int minimumPosition(int[] a, int from)
 {
int minPos = from;
for (int i = from + 1; i < a.length; i++)
{
if (a[i] < a[minPos]) { minPos = i; }
}
 return minPos;
 }
}

【问题讨论】:

  • 你能分享一些代码,以便我们了解这个问题的一些背景吗?
  • 你正在努力。告诉我们你为什么写i = from + 1
  • 因为您正在尝试找到最小值并且您不需要将 a[from] 与自身进行比较。基本上是一个小优化。

标签: java sorting selection


【解决方案1】:

文档已经告诉您为什么它是i = from +1 而不是i = 0。文档:Finds the smallest element in a tail range of the array.

由于该方法找到了尾随from 的最小元素,因此循环仅比较位于from 或更大位置的每个元素。由于a[from] 是初始最小值,您可以从位置from+1 开始比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-09
    • 1970-01-01
    • 2018-11-10
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-20
    相关资源
    最近更新 更多