DS Homework 7-1 Sort with Swap(0, i)

来源:互联网 发布:白寿彝 知乎 编辑:程序博客网 时间:2024/06/05 20:56

Problem:

Given any permutation of the numbers {0, 1, 2,…, N−1}, it is easy to sort them in increasing order. But what if Swap(0, *) is the ONLY operation that is allowed to use? For example, to sort {4, 0, 2, 1, 3} we may apply the swap operations in the following way:
Swap(0, 1) => {4, 1, 2, 0, 3}
Swap(0, 3) => {4, 1, 2, 3, 0}
Swap(0, 4) => {0, 1, 2, 3, 4}
Now you are asked to find the minimum number of swaps need to sort the given permutation of the first N nonnegative integers.

Analysis:

According to the mean of the question, the only operation we can use is Swap(0, *), however we must use T(N) to find where the 0 is, so the sort program may use T(N^2), which is unacceptable.

In my program, I usewhile (A[0] != 0)to make A[0]=0, then find the first number which is not in right place to change with A[0]. Besides I use a static variable i in function FindNot to save much time.

Code:

#include <stdio.h>#include <stdlib.h>int FindNot(int* A, int N);int main(void){    //freopen("test.txt", "r", stdin);    int N, Temp, i, count = 0;    scanf("%d", &N);    int A[N];    for (i = 0; i < N; i++)        scanf("%d", &A[i]);    while (1) {        while (A[0] != 0) {            Temp = A[0];            A[0] = A[Temp];            A[Temp] = Temp;            count++;        }        Temp = FindNot(A, N);        if (Temp == 0)  break;        A[0] = A[Temp];        A[Temp] = 0;        count++;    }    printf("%d\n", count);    return 0;}int FindNot(int* A, int N){    int i;    for (i = 1; i < N; i++)        if (A[i] != i)            return i;    return 0;}