【发布时间】:2018-06-12 07:34:05
【问题描述】:
我是 CS 的新学生。现在我正在自学编程入门。我正在研究选择排序算法,我认为通过在下面对选择排序进行这种更改,它会提高效率,这是真的还是我遗漏了什么? 改变不是每次都调用swap函数,即使数组没有变化,我们可以添加changeMade布尔变量,我们只在数组发生变化时使用它来调用函数。如有错误请指正
Declare Integer startScan, i, minValue
Declare Integer minIndex
//the boolean variable
//that could make algorithim
//more efficient
Declare Boolean changemade
//Declare the array and Declare it is size
//and initialize it
Constant Integer SIZE = 5
Declare Integer array[SIZE]=1, 4, 8, 2, 5
For StartScan = 0 To SIZE-2
set changeMade = False
set array[startScan]= minValue
For i= startScan+1 To SIZE-1
If array[i]<minValue Then
set minValue=array[i]
set minIndex= i
set changeMade=True //the modification
End If
End For
If ChangeMade = True Then
call swap(array[minIndex], array[startScan])
End For
Module swap(Integer Ref a, Integer Ref b)
Declare Integer temp
set temp = a
set a = b
set b = temp
End Module
【问题讨论】:
-
如果你查看算法的实现,其实已经是这样了。这个想法是:遍历每个元素,从当前索引开始从列表中选择最小元素,如果它不是当前元素,则将其与当前元素交换。您的
ChangeMade变量只是检查最小索引是否与当前索引相同的实现。 -
您的更改可能更有效率,但可能会更昂贵。如果在一次迭代中进行了许多更改,您最终不得不多次设置
ChangeMade标志。也许更好的优化是将changeMade检查替换为If minIndex <> startScan。你不需要changeMade标志。
标签: algorithm computer-science selection-sort