-
Notifications
You must be signed in to change notification settings - Fork 0
/
25. Using two queue for haivg sorted_queue like priority queue.c
90 lines (77 loc) · 1.9 KB
/
25. Using two queue for haivg sorted_queue like priority queue.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <stdio.h>
#define MAX 100 // Adjust MAX as needed
int queue[MAX], front = -1, rear = -1;
int queue1[MAX], front1 = -1, rear1 = -1;
int isFull() {
return rear == MAX - 1;
}
int isEmpty() {
return front == -1 || front > rear;
}
int enqueue(int data) {
if (isFull()) {
printf("Queue Overflow.\n");
return 0;
} else {
if (front == -1)
front = 0;
rear++;
queue[rear] = data;
return 1;
}
}
int dequeue() {
int data;
if (isEmpty()) {
printf("Queue Underflow.\n");
return 0;
} else {
data = queue[front];
front++;
return data;
}
}
void transferAndPrintSorted() {
front1 = -1; // Initialize front1
rear1 = -1; // Initialize rear1
while (!isEmpty()) {
int temp = dequeue();
int found = 0; // Flag to indicate if temp is placed in queue1
// Find the correct position for temp in queue1 (increasing order)
for (int i = front1; i <= rear1; i++) {
if (temp < queue1[i]) {
// Shift elements in queue1 one position ahead
for (int j = rear1; j >= i; j--) {
queue1[j + 1] = queue1[j];
}
queue1[i] = temp;
found = 1;
rear1++; // Increase rear1 after inserting
break; // Exit loop after placing temp
}
}
// If temp wasn't placed in queue1 due to being larger than all elements,
// enqueue it at the end if there's space
if (!found && rear1 != MAX - 1) {
rear1++;
queue1[rear1] = temp;
} else if (!found && rear1 == MAX - 1) {
printf("Queue1 Overflow.\n");
return;
}
}
printf("Elements in sorted order in queue1: ");
for (int i = 0; i <= rear1; i++) {
printf("%d ", queue1[i]);
}
printf("\n");
}
int main() {
enqueue(30);
enqueue(10);
enqueue(90);
enqueue(616);
enqueue(77);
transferAndPrintSorted();
return 0;
}