values = [3, 1, 2]
i = 0
while i < 2
smallest = i
j = i + 1
while j < 3
if values[j] < values[smallest]
smallest = j
end
j += 1
end
saved = values[i]
values[i] = values[smallest]
values[smallest] = saved
i += 1
end
i = 0
while i < 3
puts values[i]
i += 1
end
输出
1
2
3
生活中的例子
先装较轻的包裹
三个包裹分别重8、3和5千克。第一个装车的位置该放哪个?
初始状态8 3 5
结果3 8 5
把三个包裹都看一遍,再把重量为3的包裹与最前面的包裹交换。
找出最早的日期
未整理的表格上分别写着 9 日、12 日、4 日。按日期整理时,哪一天的表应放进第一个托盘?
初始状态9 12 4
结果4
如果只看前两张表上的日期,就会漏掉 4 日。
直接在书架上整理图书
书 1 和 2 的位置已经定好,只剩下书 5 和 3。接下来要检查哪一段?
初始状态1 2 • 5 3
结果1 2 3 5
已经排好的前段不用动。从剩下的那一对中选3,把它放到该在的位置。
开销与局限
即使剩下的元素已经有序,选择排序仍会把它们检查一遍。需要O(n²)次比较,最多交换n−1次。
时间复杂度
最好情况: Θ(n²)
平均情况: Θ(n²)
最坏情况: Θ(n²)
用 Ruby 实现选择排序
Ruby 源代码
class SelectionSortExample
def selectionSort(arr)
for i in 0...arr.length do
minIndex = i
for j in (i+1)...arr.length do
if(arr[minIndex] > arr[j])
minIndex = j
end
end
temp = arr[minIndex]
arr[minIndex] = arr[i]
arr[i] = temp
end
end
def printArray(arr)
for i in 0...arr.length do
print(arr[i].to_s + " ")
end
puts("")
end
end
obj = SelectionSortExample.new
arr = [15, 3, 12, 6, -9, 9, 0]
print("Before Sorting: ")
obj.printArray(arr)
obj.selectionSort(arr)
print("After Sorting: ")
obj.printArray(arr)
输出
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
广告
一步步看例子
从 [15, 3, 12, 6, -9, 9, 0] 开始。
从下标0开始。扫描剩下的值,记住最小值(−9)所在的位置。
交换两个值:−9和第一项15。第一项的位置就确定了。
从下一个位置重复。只剩一项时,整个数组就已经排好序。
用 Ruby 实现选择排序:逐步讲解
Ruby 源代码
class SelectionSortExample
def selectionSort(arr)
# Loop all the element in an array except the last element
for i in 0...(arr.length - 1) do
minIndex = i
# Find an index of a lowest element in the right-hand side
# corresponding to the element arr[i].
for j in (i+1)...arr.length do
if(arr[minIndex] > arr[j])
minIndex = j
end
end
# Swap the lowest element with the current element (i.e. arr[i] <=> arr[minIndex])
temp = arr[minIndex]
arr[minIndex] = arr[i]
arr[i] = temp
end
end
def printArray(arr)
# Loop the item and print each item in the console with white space seperated
for i in 0...arr.length do
print(arr[i].to_s + " ")
end
puts("")
end
end
obj = SelectionSortExample.new
arr = [15, 3, 12, 6, -9, 9, 0]
print("Before Sorting: ")
obj.printArray(arr)
obj.selectionSort(arr)
print("After Sorting: ")
obj.printArray(arr)
输出
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15