您的位置:首页 > 其它

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

2017-12-23 14:01 106 查看

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 use
while (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
;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: