How to sort an array using minimum number of writes?

后端 未结 5 1890
再見小時候
再見小時候 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:30

    If the array is shorter (ie less than about 100 elements) a Selection sort is often the best choice if you also want to reduce the number of writes.

    From wikipedia:

    Another key difference is that selection sort always performs Θ(n) swaps, while insertion sort performs Θ(n2) swaps in the average and worst cases. Because swaps require writing to the array, selection sort is preferable if writing to memory is significantly more expensive than reading. This is generally the case if the items are huge but the keys are small. Another example where writing times are crucial is an array stored in EEPROM or Flash. There is no other algorithm with less data movement.

    For larger arrays/lists Quicksort and friends will provide better performance, but may still likely need more writes than a selection sort.

    If you're interested this is a fantastic sort visualization site that allows you to watch specific sort algorithms do their job and also "race" different sort algorithms against each other.

提交回复
热议问题