c语言实现一个先入先出的队列,长度为20,并定义一个同样长度的数组,来临时保存队列中的数据,然后对数组的数据进行排序
时间: 2023-05-25 11:01:46 浏览: 56
A:
以下是一个C语言实现先入先出队列的代码示例:
```
#include <stdio.h>
#define MAX_SIZE 20
int queue[MAX_SIZE];
int rear = -1, front = -1;
void enqueue(int data) {
if(rear == MAX_SIZE - 1) {
printf("队列已满.\n");
return;
}
if(front == -1) {
front = 0;
}
rear++;
queue[rear] = data;
printf("%d 已被插入到队列中.\n", data);
}
void dequeue() {
if(front == -1 || front > rear) {
printf("队列为空.\n");
return;
}
printf("%d 已被移出队列.\n", queue[front]);
front++;
}
void display() {
if(front == -1) {
printf("队列为空.\n");
return;
}
for(int i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
printf("\n");
}
void bubble_sort() {
int temp;
for(int i = 0; i < rear; i++) {
for(int j = 0; j < (rear - i); j++) {
if(queue[j] > queue[j + 1]) {
temp = queue[j];
queue[j] = queue[j + 1];
queue[j + 1] = temp;
}
}
}
}
int main() {
int choice, data;
while(1) {
printf("1. 插入元素\n");
printf("2. 移出元素\n");
printf("3. 显示队列\n");
printf("4. 对队列进行排序\n");
printf("5. 退出\n");
printf("请输入选项: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("请输入需要插入的元素:");
scanf("%d", &data);
enqueue(data);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
bubble_sort();
printf("队列已排序.\n");
break;
case 5:
printf("程序已退出.\n");
return 0;
default:
printf("无效的选项.\n");
}
}
return 0;
}
```
此代码演示了一个先入先出队列的基本操作,包括插入元素、移出元素、显示队列和对队列进行排序。
使用冒泡排序算法,对队列中的数据进行排序:
```
void bubble_sort() {
int temp;
for(int i = 0; i < rear; i++) {
for(int j = 0; j < (rear - i); j++) {
if(queue[j] > queue[j + 1]) {
temp = queue[j];
queue[j] = queue[j + 1];
queue[j + 1] = temp;
}
}
}
}
```
这里使用了简单的冒泡排序算法,对数组中的元素进行排序。可以将其放在主函数中,通过选择“对队列进行排序”来运行它。
注意,在上述代码中,队列的长度限制是20。如果需要调整队列长度,只需修改`#define MAX_SIZE 20`这行代码中定义的值即可。