Created
November 20, 2025 05:27
-
-
Save sortira/3ce129bac8a67d00dfb71f88fd79aa6d to your computer and use it in GitHub Desktop.
sort stack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #define MAX_SIZE 100 | |
| typedef struct { | |
| int buffer[MAX_SIZE]; | |
| int top; | |
| } stack; | |
| void init(stack* s) { | |
| s->top = -1; | |
| } | |
| int isEmpty(stack* s) { | |
| return s->top == -1; | |
| } | |
| int isFull(stack* s) { | |
| return s->top == MAX_SIZE - 1; | |
| } | |
| void push(stack* s, int val) { | |
| if (!isFull(s)) | |
| s->buffer[++s->top] = val; | |
| } | |
| int pop(stack* s) { | |
| if (!isEmpty(s)) | |
| return s->buffer[s->top--]; | |
| return -1; | |
| } | |
| int peek(stack* s) { | |
| if (!isEmpty(s)) | |
| return s->buffer[s->top]; | |
| return -1; | |
| } | |
| void insert_element(stack* st, int element) { | |
| if (isEmpty(st) || element >= peek(st)) { | |
| push(st, element); | |
| return; | |
| } | |
| int top_element = pop(st); | |
| insert_element(st, element); | |
| push(st, top_element); | |
| } | |
| void sort(stack* st) { | |
| if (isEmpty(st)) { | |
| return; | |
| } | |
| int top_element = pop(st); | |
| sort(st); | |
| insert_element(st, top_element); | |
| } | |
| void printStack(stack* s) { | |
| if (isEmpty(s)) return; | |
| int temp = pop(s); | |
| printStack(s); | |
| printf("%d ", temp); | |
| push(s, temp); | |
| } | |
| void merge_and_sort(stack* s, stack* p) { | |
| while(!isEmpty(p)) { | |
| push(s, pop(p)); | |
| } | |
| sort(s); | |
| printf("merged stack sorted:\n "); | |
| printStack(s); | |
| printf("\n"); | |
| } | |
| int main() { | |
| int n; | |
| printf("Enter the size of the stack:\n"); | |
| scanf("%d", &n); | |
| printf("Enter a stack:\n"); | |
| stack* s = (stack*) malloc(sizeof(stack)); | |
| init(s); | |
| for(int i = 0; i < n; i++) { | |
| int elem; | |
| scanf("%d", &elem); | |
| push(s, elem); | |
| } | |
| printf("Stack: \n"); | |
| printStack(s); | |
| printf("\n"); | |
| printf("Enter the size of the stack:\n"); | |
| scanf("%d", &n); | |
| printf("Enter a stack:\n"); | |
| stack* p = (stack*) malloc(sizeof(stack)); | |
| init(p); | |
| for(int i = 0; i < n; i++) { | |
| int elem; | |
| scanf("%d", &elem); | |
| push(p, elem); | |
| } | |
| printf("Stack: \n"); | |
| printStack(p); | |
| printf("\n"); | |
| merge_and_sort(s, p); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment