昨天我在类里面收到了这份作业,以为我了解选择排序的过程,但是现在我对此有些不确定。我认为每次通过之后,左边的数字都会被排序,并且直到右边的所有数字都首先被排序后才会再次检查。

以下是说明和我的答案:


Original Array: 30 8 2 25 27 20
PASS 1: 8 30 2 25 27 20
PASS 2: 8 2 30 25 27 20
PASS 3: 8 2 25 30 27 20
PASS 4: 8 2 25 27 30 20
PASS 5: 8 2 25 27 20 30

有人可以告诉我我做得对吗?

最佳答案

在伪代码中:

Repeat until no unsorted elements remain:
    Search the unsorted part of the data to find the smallest value
    Swap the smallest found value with the first element of the unsorted part

据此,您的数据列表将是...
Original Array: 30 8 2 25 27 20

P1: [2] 8 30 25 27 20 // smallest(2), swap this with the first value(30)

P2: [2 8] 30 25 27 20 // smallest(8), don't need to swap

P3: [2 8 20] 25 27 30 // smallest(20), swap this with the first ele of unsorted list(30)

P4: [2 8 20 25] 27 30 // smallest(25), don't need to swap

P5: [2 8 20 25 27] 30 // smallest(27), don't need to swap

P6: [2 8 20 25 27 30] // smallest(30), don't need to swap... sorted!

由于最后一个元素已经被排序,因此不需要PASS 6。

观看CS50的这段视频(哈佛大学对此进行了很好的解释):https://www.youtube.com/watch?v=3hH8kTHFw2A

关于java - 需要帮助了解选择排序算法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50006841/

10-12 00:31
查看更多