Блог пользователя hasanb

Автор hasanb, история, 10 лет назад, По-английски

The problem is what's the minimum amount of reverse so the array become sorted. I observed in the worst case answer is N-1. But how can I solve the problem?

  • Проголосовать: нравится
  • +15
  • Проголосовать: не нравится

»
10 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

How did you come to the conclusion that the worst case is N?

  • »
    »
    10 лет назад, скрыть # ^ |
    Rev. 3  
    Проголосовать: нравится +10 Проголосовать: не нравится

    I think it's based on that the worst case would be you having to make a reverse in order to put every single element in it's place. For example: 2 3 1

    First, you see the number 1 is in the wrong position so you use a reverse to make it 1 3 2

    Second, you see the number 2 is in the wrong position so you use a reverse to make it 1 2 3

    So, at most you will need N — 1 operations on the worst case, following this strategy: For each element which is not in it's right place, reverse a segment starting with the index where you want to put the number, and ending with the index the number is currently at.

»
10 лет назад, скрыть # |
Rev. 4  
Проголосовать: нравится -17 Проголосовать: не нравится

Find i, such that ai is the smallest element of array a among index 1 to n. Then if you reverse a1 to ai, you have the smallest element of a at a1. Again, find the smallest among a2 to an and reverse a2 to ai to bring the 2nd smallest to the 2nd position... and so on...

UPD: This will sort the array using exactly n reverses. Minimum number of needed reverses may be less. So this does not help you finding minimum number of reverse operations. It's only useful if you are allowed to do up to n reverse operations.

»
10 лет назад, скрыть # |
Rev. 2  
Проголосовать: нравится +55 Проголосовать: не нравится

What can you reverse?

»
10 лет назад, скрыть # |
 
Проголосовать: нравится +5 Проголосовать: не нравится

This problem asks what you want. Sort the array with maximum n swaps.

I solved this problem using method similar to selection sort.

Start from first index, find minimum element in the array then swap it with first index. Do same for other indexes. Maximum n swaps.

Code

»
10 лет назад, скрыть # |
Rev. 2  
Проголосовать: нравится +19 Проголосовать: не нравится

As linked by cgy4ever your problem is the pancake flipping problem which is NP-Hard, sadly. Anyone who proposes some solution that is polynomial here is most likely wrong.