#include <stdlib.h>
typedef struct node
{ // 候選人結構
char name[8];
int num;
int score;
int tax;
}Node;
void shellSort( Node **, int );
int main(void)
{
int n = 0;
Node * pArray[9]={};//指針數組,長度9
int count = 0;
//int status = 1;
int vote = -1;
printf("Input the number of the candidates(1-9):\n");
scanf("%d", &n);
while(getchar()!='\n')
{
;
}
while (n>9 || n<1)
{
if (n>9)
{
printf("No, there cannot be so many candidates. Retry.\n");
}
else
{
printf("No candidates? It cannot be! Retry!\n");
}
scanf("%d", &n);
while(getchar()!='\n')
{
;
}
}
for (count=0; count<n; count++)
{
pArray[count] = (Node *)malloc(sizeof(Node));
pArray[count]->num = count+1;
pArray[count]->tax = 0;
pArray[count]->score = 0;
printf("Input No.%d candidate's name:\n", count+1);
gets(pArray[count]->name);
}
while (vote)
{
printf("Now, let us vote:\n*************\n");
for (count=0; count<n; count++)
{
printf("%d. %s\n", count+1, pArray[count]->name);
}
printf("0.quit\n*************\n");
scanf("%d", &vote);
while(getchar()!='\n')
{
;
}
while (vote<0 || vote>n)
{
printf("No joke, thank you. Revote.\n");
scanf("%d", &vote);
while(getchar()!='\n')
{
;
}
}
if (vote>0&&vote<=n)
{
pArray[vote-1]->score++;
}
}
printf("Finish voting. Let's find the winner......\n\n");
shellSort( pArray, n );
for (count=0; count<n; count++)
{
pArray[count]->tax=count+1;
printf("%d. %s %d votes.\n", count+1, pArray[count]->name, pArray[count]->score);
}
for(count=0; count<n; count++)
{
free(pArray[count]);
pArray[count] = NULL;
}
return 0;
}
void shellSort( Node *p[], int len )
{
const int Length = len;
int i = 0;
int j = 0;
int gap = 0;
Node *temp = NULL;
gap = Length/2;
while (gap>0)
{
for (i=gap; i<Length; i++)
{
j = i - gap;
temp = *(p+i);
while ( (j>=0) && (p[j]->score < temp->score) )
{
*(p+j+gap) = *(p+j);
j = j - gap;
}
*(p+j+gap) = temp;
}
gap /= 2;
}
}
運行與輸入方式:
1.程序提示,輸入候選人人數, 輸入數字(1-9),大於9或小於1或者輸入不合法字符會提示錯誤。
2.程序提示依次輸入候選人名字,不能超過7個字符(少了點,妳題目給的,數組拉長點會更安全些)
3.按照程序提示的數字開始投票,或者退出。
4.投票過程結束後,程序調用shellSort(希爾排序)函數對所有參選人按照得票數目進行降序排序,並將排序結果輸出。