How to sort an array using minimum number of writes?

后端 未结 5 1874
再見小時候
再見小時候 2020-12-23 18:10

My friend was asked a question in his interview:

The interviewer gave him an array of unsorted numbers and asked him to sort. The restriction is that the number of w

5条回答
  •  攒了一身酷
    2020-12-23 18:34

    You can use a very naive algorithm that satisfies what you need.

    The algorithm should look like this:

    i = 0
    
    do
       search for the minimum in range [i..n)
       swap a[i] with a[minPos]
       i = i + 1
    repeat until i = n.
    

    The search for the minimum can cost you almost nothing, the swap costs you 3 writes, the i++ costs you 1..

    This is named selection sort as stated by ash. (Sorry, I didn't knew it was selection sort :( )

提交回复
热议问题