Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

python - Give the state of the list after the first three iterations of the main/outer loop of the selection-sort algorithm

So our list that hey give us is

A = [12,6,5,8,10,3,8,2]

We don't have to code anything, just write our answers in a text file. My guess is that the list would be in order after the main/outer loop of the selection sort so my ans would be

[2,3,5,6,,8,8,10,12]

I think this is wrong though


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In selection sort, we maintain two sub-arrays out of our original array: the sorted part and the unsorted part. A = [12,6,5,8,10,3,8,2] this is your initial array

iteration 1: 
      sorted subarray             unsorted subarray
             12                    6,5,8,10,3,8,2
 Result       2                    6,5,8,10,3,8,12

we search for the minimum element in our unsorted subarray which is 2. swap 2 with 12 here.

2nd iteration: we will now consider the first element in the unsorted subarray as our second element of sorted array. Note that position of 2 is established because it is the minimum element of the entire array.Again, we search for the smallest element in our unsorted subarray and compare with the second element of sorted subarray. If the former is smaller we swap both of them.

iteration 2:
             sorted subarray          unsorted subarray
                   2,6                   5,8,10,3,8,12
        Result     2,3                   5,8,10,6,8,12

There is no element in unsorted subarray smaller than 5 so it stays the same. so, after 3 iterations the final state would be: 2,3,5,8,10,6,8,12

iteration 3:
    sorted subarray          unsorted subarray
          2,3,5                 8,10,3,8,12
Result    2,3,5                 8,10,6,8,12

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...