How to sort an array using minimum number of writes?

后端 未结 5 1892
再見小時候
再見小時候 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 18:24

    One option for large arrays is as follows (assuming n elements):

    1. Initialize an array with n elements numbered 0..n-1
    2. Sort the array using any sorting algorithm. As the comparison function, compare the elements in the input set with the corresponding numbers (eg, to compare 2 and 4, compare the 2nd and 4th elements in the input set). This turns the array from step 1 into a permutation that represents the sorted order of the input set.
    3. Iterate through the elements in the permutation, writing out the blocks in the order specified by the array. This requires exactly n writes, the minimum.

    To sort in-place, in step 3 you should instead identify the cycles in the permutation, and 'rotate' them as necessary to result in sorted order.

提交回复
热议问题