Sort a move to end list

前端 未结 2 1323
遥遥无期
遥遥无期 2021-01-27 11:50

A sequential unique list of numbers (1,2,3,...,n) has been randomized and I need to sort it by moving one item at a time to the end of the list. Which algorithm will provide th

2条回答
  •  执笔经年
    2021-01-27 12:10

    Here's an algorithm:

    1. Check the length of the list (from the beginning) till which it is increasing, i.e., stop when the list starts to decrease.
    2. Subtract that length from the length of the list. And that is your answer.

    Quite intuitive, just think about it. Example:

    12345 -> 25341
    |25| is in increasing order and after that it becomes decreasing.
    Length (2,5) = 2
    Answer = 5 - 2 = 3
    

    If your list isn't sorted in increasing order, you could always map it via indices.

提交回复
热议问题