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.
Format of functions:
void MySort( ElementType A[], int N );
where ElementType A[] contains the N elements.
Sample program of judge:
#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 */
Sample Input:
6
2 2 0 1 0 0
Sample Output:
false in A[0]-A[0]
maybe in A[1]-A[2]
true in A[3]-A[5]
源码:
//用了桶排,纯当作练习
struct Bnode{
int front;
int rear;
}Bucket[3];
void assign(int b,int index,int next[])
{
if(Bucket[b].front<0)
Bucket[b].front=index;
else
next[Bucket[b].rear]=index;
Bucket[b].rear=index;
}
void MySort( ElementType A[], int N )
{
for(int i=0;i<3;i++)
{
Bucket[i].front=Bucket[i].rear=-1;
}
int next[N];
for(int i=0;i<N;i++)
next[i]=-1;
for(int i=0;i<N;i++)
{
assign(A[i],i,next);
}
int t;
if(Bucket[1].front>=0)
{
t=Bucket[1].front;
if(Bucket[2].front>=0)
{
next[Bucket[1].rear]=Bucket[2].front;
if(Bucket[0].front>=0)
next[Bucket[2].rear]=Bucket[0].front;
}
else if(Bucket[0].front>=0)
{
next[Bucket[1].rear]=Bucket[0].front;
}
}
else if(Bucket[2].front>=0)
{
t=Bucket[2].front;
if(Bucket[0].front>=0)
next[Bucket[2].rear]=Bucket[0].front;
}
else if(Bucket[0].front>=0)t=Bucket[0].front;
ElementType temp[N];
for(int i=0;i<N;i++)
{
temp[i]=A[t];
t=next[t];
}
for(int i=0;i<N;i++)
A[i]=temp[i];
}