为什么选择排序方法以“i = from + 1”开始循环

时间:2016-10-24 17:21:09

标签: java sorting selection

我正在使用选择短方法对数组进行排序。该方法使用以“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;
 }
}

1 个答案:

答案 0 :(得分:0)

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

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