7-20 Sort with Swap(0, i) (25分)

topic

Here Insert Picture Description

analysis:

Sequence can be found by several rings, the elements in each ring can be sorted such that the inner ring element in the correct position, the sample can be found go again, in a ring element exchange requires a minimum number of elements -1-order operation can be sorted, because the only 0 and exchange, if the ring includes 0, then the number of elements need to be exchanged -1-order, otherwise, we need to exchange 0 into the ring, and then swap out elements need to be exchanged -1 + 2 + 1 number of times that is the number of elements. Then do not exchange if an element already in place.

Code:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n,s[100000],ans = 0;
    scanf("%d",&n);
    for(int i = 0;i < n;i ++) {
        scanf("%d",&s[i]);
    }
    for(int i = 0;i < n;i ++) {
        int k = s[i];
        int c = 0;
        while(s[k] != k) {
            c ++;
            int t = k;
            k = s[k];
            s[t] = t;
        }
        if(c == 0) continue;
        if(i == 0) ans += c - 1;
        else ans += c + 1;
    }
    printf("%d",ans);
}
Published 61 original articles · won praise 7 · views 3617

Guess you like

Origin blog.csdn.net/weixin_42469716/article/details/105182407