Suppose you have an array of N elements, containing three distinct keys, "true", "false", and "maybe". Given an O(N) algorithm to rearrange the list so that all "false" elements precede "maybe" elements, which in turn precede "true" elements. You may use only constant extra space.
假设您有一个 N 个元素的数组,其中包含三个不同的键,“true”、“false”和“maybe”。给定一个 O(N) 算法来重新排列列表,以便所有“假”元素都位于“可能”元素之前,而“可能”元素又在“真”元素之前。您只能使用恒定的额外空间。
Format of functions:
void MySort( ElementType A[], int N );
#include <stdio.h>
#include <stdlib.h>
typedef enum { true, false, maybe } Keys;
typedef Keys ElementType;
void Read( ElementType A[], int N ); /* details omitted */
void MySort( ElementType A[], int N );
void PrintA( ElementType A[], int N )
{
int i, k;
k = i = 0;
for ( ; i<N && A[i]==false; i++ );
if ( i > k )
printf("false in A[%d]-A[%d]\n", k, i-1);
k = i;
for ( ; i<N && A[i]==maybe; i++ );
if ( i > k )
printf("maybe in A[%d]-A[%d]\n", k, i-1);
k = i;
for ( ; i<N && A[i]==true; i++ );
if ( i > k )
printf("true in A[%d]-A[%d]\n", k, i-1);
if ( i < N )
printf("Wrong Answer\n");
}
int main()
{
int N;
ElementType *A;
scanf("%d", &N);
A = (ElementType *)malloc(N * sizeof(ElementType));
Read( A, N );
MySort( A, N );
PrintA( A, N );
return 0;
}
/* Your function will be put here */
输入样例:
6 2 2 0 1 0 0
输出样例:
false in A[0]-A[0]
maybe in A[1]-A[2]
true in A[3]-A[5]
思路:这道题就是按他要求的:先false(1)再maybe(2)最后true(0)来进行排序;
首先遍历一遍原数组A,将0,1,2出现的次数对应记录到新建的数组sum[3]中。
最后从头对A[ ] 按照sum[2],sum[1],sum[0]所记录的值重新赋值。
void MySort( ElementType A[], int N )
{
int sum[3]={0};
for(int i=0;i<N;i++)
{
switch(A[i])
{
case 1:
sum[1]++;
break;
case 2:
sum[2]++;
break;
case 0:
sum[0]++;
break;
default: break;
}
}
for(int i=0;i<N;i++)
{
while(sum[1])
{
sum[1]--;
A[i++]=1;
}
while(sum[2])
{
sum[2]--;
A[i++]=2;
}
while(sum[0])
{
sum[0]--;
A[i++]=0;
}
}
}