使用一个辅助的队列和非数组变量设计一个算法以使队列中的元素有序

/*使用一个辅助的队列和非数组变量设计一个算法以使队列中的元素有序*/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define OK 1
#define ERROR 0
#define MAXSIZE 20
typedef int QElemType;
typedef int Status;

typedef struct 
{
    QElemType data[MAXSIZE];
    int front;
    int rear;
}SqQueue;


//循环队列的初始化
Status InitSqQueue(SqQueue * S)
{
    S->front=0;
    S->rear=0;
    return OK;
}

//循环队列的建立
Status create(SqQueue * S,int n)
{
    srand((unsigned)time(NULL));
    for(int i=0;i<n;i++)
    {
        S->data[i]=rand()%100;
        S->rear++;
    }

    return OK;
}

//循环队列的入队
Status EnQueue(SqQueue * S,QElemType e)
{   
    S->data[S->rear]=e;
    S->rear=(S->rear+1)%MAXSIZE;
    return OK;
}


//循环队列的出队
Status DeQueue(SqQueue * S,QElemType * e)
{
    *e=S->data[S->front];
    S->front=(S->front+1)%MAXSIZE;
    return OK;
}


//循环队列的长度
Status Length(SqQueue * S)
{
    return (S->rear-S->front+MAXSIZE)%MAXSIZE;
}



//输出
void print(SqQueue * S)
{
    printf("输出元素:\n");
    int length=(S->rear-S->front+MAXSIZE)%MAXSIZE;
    for(int i=S->front;i<length;i++)
    {
        printf("%d ",S->data[i]);
    }
    printf("\n");
}

//找出最大元素
Status GetMax(SqQueue * S)
{

    int length=Length(S);
    int temp=S->front;
    for(int i=S->front+1;i<length+S->front;i++)//关键句,重点是加上S->front!!!!!
    {
        if(S->data[temp]<S->data[i])
        {
            temp=i;
        }
    }
    return temp;
}

//把最大元素和front(data[0])元素进行交换,然后出队,入队进新的队列里
Status SwapMax(SqQueue * S,SqQueue * L)
{
    QElemType DeElem;
    int temp;
    int Index=GetMax(S);
    temp=S->data[Index];
    S->data[Index]=S->data[S->front];
    S->data[S->front]=temp;
    DeQueue(S,&DeElem);
    EnQueue(L,DeElem);
    return OK;
}

//排序
Status Sort(SqQueue * S,SqQueue * L)
{
    QElemType DeElem;
    int length=Length(S);
    for(int i=0;i<length;i++)
    {
        SwapMax(S,L);
    }
    InitSqQueue(S); //这一步是重新初始化队列S(或者完善初始化函数)
    for(int j=0;j<length;j++)
    {
        DeQueue(L,&DeElem);
        EnQueue(S,DeElem);
    }
    return OK;
}


int main()
{
    SqQueue S,L;
    int ElemNumber;
    InitSqQueue(&S);
    InitSqQueue(&L);
    printf("输入元素个数:\n");
    scanf("%d",&ElemNumber);
    create(&S,ElemNumber);
    print(&S);
    Sort(&S,&L);
    print(&S);
    return 0;
}

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值