0% found this document useful (0 votes)
12 views22 pages

DS ExternalLab

Uploaded by

anuragthippani8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views22 pages

DS ExternalLab

Uploaded by

anuragthippani8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

DS External Lab

Bubble Sort:
a = [64, 34, 25, 12, 22, 11, 90]
print("Before sorting: ", a)

for i in range(len(a)):
for j in range(0, len(a)-i-1):
if a[j] > a[j+1]:
a[j], a[j+1] = a[j+1], a[j]

print("After sorting: ", a)

selection sort:
a = [16, 10, -1, 369, 5]

for i in range(len(a)):
# Find the index of the minimum value in the unsorted part of the list
min_index = i
for j in range(i + 1, len(a)):
if a[j] < a[min_index]:
min_index = j

# Swap the found minimum element with the first element


a[i], a[min_index] = a[min_index], a[i]

print(a)

Insertion sort:
a = [12, 111, 13, 5, 6]

for i in range(1, len(a)):


temp = a[i]
j=i-1
while j >= 0 and a[j] > temp:
a[j + 1] = a[j]
j=j-1
a[j + 1] = temp

print(a)
merge sort:

def mergesort(a):
mid = len(a) // 2
left = a[:mid]
right = a[mid:]

if len(left) > 1:
left = mergesort(left)
if len(right) > 1:
right = mergesort(right)

c = []
while left and right:
if left[-1] >= right[-1]:
c.append(left.pop())
else:
c.append(right.pop())

c.reverse()
return (left or right) + c

a = [54, 26, 93, -17, 1]


print(mergesort(a))

linear search:

a = [20, 33, 140, -5, 69, 997, 89]


search = eval(input("Enter an element to search: "))

if search in a:
print("Element found at index:", a.index(search))
else:
print("Not found")
Binary search:

a = [20, 33, 140, -5, 69, 997, 89]


a.sort()
print("Sorted List =", a)

search = eval(input("Enter Search Number: "))


start = 0
stop = len(a) - 1

while start <= stop:


mid = (start + stop) // 2

if search == a[mid]:
print(search, "element found at the position", mid)
break
elif search < a[mid]:
stop = mid - 1
else:
start = mid + 1
else:
print("Element not found")

Stack using array:

#include <stdio.h>
#include <stdlib.h>
#define MAX 100
struct Stack {
int top;
int array[MAX];
};
void initialize(struct Stack* stack) {
stack->top = -1;
}
int isEmpty(struct Stack* stack) {
return (stack->top == -1);
}
int isFull(struct Stack* stack) {
return (stack->top == MAX - 1);
}
void push(struct Stack* stack, int item) {
if (isFull(stack)) {
printf("Stack Overflow\n");
return;
}
stack->array[++stack->top] = item;
printf("%d pushed to stack\n", item);
}
int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
return -1;
}
return stack->array[stack->top--];
}
int peek(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
}
return stack->array[stack->top];
}
int main() {
struct Stack stack;
initialize(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
printf("%d popped from stack\n", pop(&stack));
printf("Top element is %d\n", peek(&stack));
return 0;
}

Queue using array:


#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define size 5
int queue[size],front=-1,rear=-1,i;
int enqueue()
{
if(rear==size-1)
printf("\n Queue is Full");
else
{
printf("\n Enter number:");
scanf("%d",&queue[rear++]);
}
}
int dequeue()
{
if(front==rear)
printf("\n Queue is empty");
else
printf("\n Deleted Element is %d",queue[front++]);
}
int display()
{
if(front==rear)
printf("\n Queue is Empty");
else
{
printf("\n Queue Elements are:\n ");
for(i=front; i<rear; i++)
printf("%d \t",queue[i]);
}
}
int main()
{
int i,c;
printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
while(1)
{
printf("\nEnter the Choice:");
scanf("%d",&c);
switch(c)
{
case 1:
enqueue();
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
break;
default:
printf("Wrong Choice: please see the options");
}
}
}

Stack using linked list:


#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*top = NULL,*temp,*newnode;
void push()
{
newnode = (struct node*)malloc(sizeof(struct node));
printf("\n Enter Element : ");
scanf("%d",&newnode->data);
if(top == NULL)
newnode->next = NULL;
else
{
newnode->next = top;
}
top = newnode;
printf("\nInsertion is Success!!!\n");
}
void pop()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else
{
temp = top;
printf("\nDeleted element: %d", top->data);
top = top->next;
free(temp);
}
}
void display()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else
{
temp = top;
while(temp != NULL)
{
printf("%d--->",temp->data);
temp = temp -> next;
}
}
}
int main()
{
int choice;
printf("\n:: Stack using Linked List ::\n");
while(1)
{
printf("\n****** MENU ******\n");
printf("1. Push\n2. Pop\n3. Display \n4. Peek \n5. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: push(); break;
case 2: pop(); break;
case 3: display(); break;
case 4: printf("\n Peek of the stack = %d",top->data); break;
case 5: exit(0);
}
}
}

Queue using linked list:


#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*front = NULL,*rear = NULL,*newnode,*temp;
void enqueue()
{
newnode = (struct node*)malloc(sizeof(struct node));
printf("\n Enter the Data : ");
scanf("%d",&newnode->data);
newnode -> next = NULL;
if(front == NULL)
front = rear = newnode;
else
{
rear -> next = newnode;
rear = newnode;
}
printf("\n Insertion is Success!!!\n");
}
void dequeue()
{
if(front == NULL)
printf("\n Queue is Empty!!!\n");
else
{
temp = front;
printf("\n Deleted element: %d ",front->data);
front = front -> next;
free(temp);
}
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else
{
temp = front;
while(temp != NULL)
{
printf("%d--->",temp->data);
temp = temp -> next;
}
}
}
void main()
{
int choice;
printf("\n:: Queue Implementation using Linked List ::\n");
while(1)
{
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: enqueue(); break;
case 2: dequeue(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\n Wrong selection!!! Please try again!!!\n");
}
}
}
Heap Sort:
from heapq import heappop,heappush
def heapsort(a):
heap=[]
for i in a:
heappush(heap,i)
s=[]
while heap:
s.append(heappop(heap))
return s
a=[27, 21, 55, 15, 60, 4, 11, 17, 2, 87]
print(heapsort(a))

Infix to Postfix Conversion:


#Convert Infix Expression to Postfix Expression (Using Python)
operator=['+', '-', '*', '/', '(', ')', '^'] # set of operators
priority = {'+':1, '-':1, '*':2, '/':2, '^':3} # dictionary having priorities
def infix_to_postfix(exp):
stack=[]
output=''
for i in exp:
if i not in operator:
output=output+i
elif i=='(':
stack.append('(')
elif i==')':
while stack and stack[-1]!= '(':
output=output+stack.pop()
stack.pop()
else:
while stack and stack[-1]!='(' and priority[i]<=priority[stack[-1]]:
output=output+stack.pop()
stack.append(i)

while stack:
output=output+stack.pop()
return output
exp=input("Expression ?")
print('postfix expression: ',infix_to_postfix(exp))
#Expression ?"a+b*(c^d-e)^(f+g*h)-i";
Postfix evaluation:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
int items[MAX_SIZE];
int top;
} Stack;
void push(Stack *stack, int item) {
if (stack->top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
exit(1);
}
stack->items[++stack->top] = item;
}
int pop(Stack *stack) {
if (stack->top == -1) {
printf("Stack Underflow\n");
exit(1);
}
return stack->items[stack->top--];
}
int isOperand(char ch) {
return (ch >= '0' && ch <= '9');
}
int evaluatePostfix(char postfix[]) {
Stack stack;
stack.top = -1;
char *token = strtok(postfix, " ");
while (token != NULL) {
if (isOperand(token[0]))
push(&stack, atoi(token));
else {
int operand2 = pop(&stack);
int operand1 = pop(&stack);
switch (token[0]) {
case '+':
push(&stack, operand1 + operand2);
break;
case '-':
push(&stack, operand1 - operand2);
break;
case '*':
push(&stack, operand1 * operand2);
break;
case '/':
push(&stack, operand1 / operand2);
break;
}
}
token = strtok(NULL, " ");
}
return pop(&stack);
}
int main() {
// Example usage:
char postfix[] = "2 3 1 * + 9 -";
int result = evaluatePostfix(postfix);
printf("Postfix Evaluation Result: %d\n", result);
return 0;
}

Depth First Search(DFS):

#include<stdio.h>
int v,a[50][50],visited[20],n;
void dfs(int v)
{
int i;
visited[v]=1;
for(i=0;i<n;i++)
{
if(a[v][i]!=0 && visited[i]==0) // to check adjacent and not visited
vertex
{
printf("%d ",i);
dfs(i);
}
}
}
int main()
{
int i,j;
printf("\n Enter the number of vertices :");
scanf("%d",&n);

for(i=0;i<n;i++) // not visited vertex


visited[i]=0;
printf("\n Enter adjacent matrix :\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

printf("\n Enter the starting vertex: ");


scanf("%d",&v);

printf("\n DFS Traversal is :");


printf("%d ",v);
dfs(v);
}

Breadth First Search (BFS):


#include<stdio.h>
int i,j,v,a[20][20],q[20],visited[20],n,f=-1,r=-1;
void bfs(int v)
{
for(i=0;i<n;i++)
{
if(a[v][i]!=0 && visited[i]==0) // to check adjacent and not visited
vertex
{
r=r+1;
q[r]=i;
visited[i]=1;
printf("%d ",i);
}
}
f=f+1;
bfs(q[f]);
}
int main()
{
printf("\n Enter the number of vertices :");
scanf("%d",&n);

for(i=0;i<n;i++) // not visited vertex


visited[i]=0;

printf("\n Enter adjacent matrix :\n");


for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);

printf("\n Enter the starting vertex: ");


scanf("%d",&v);

f=r=0;
q[r]=v;

printf("\n BFS Traversal is :");

visited[v]=1;
printf("%d ",v);
bfs(v);
}

Singly Linked List:(Insert at Begin Delete at End) &


(Insert at end Delete at start)
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*start=NULL,*temp,*newnode,*p;
void create() //Create function
{
int i,n;
printf("\n Enter the number of node to create");
scanf("%d",&n);
for(i=0;i<n;i++)
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\n Enter the data : ");
scanf("%d",&newnode->data);
newnode->next=NULL;
if(start==NULL)
{
start=newnode;
temp=newnode;
}
else
{
temp->next=newnode;
temp=newnode;
}
}
}
void display() //Display Function
{
printf("\n The Linked List : ");
temp=start;
while(temp!=NULL)
{
printf("%d--->",temp->data);
temp=temp->next;
}
printf("NULL");
}
void insert_at_beg()
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\n Enter the data to insert at begin: ");
scanf("%d",&newnode->data);
newnode->next=NULL;
if(start==NULL)
start=newnode;
else
{
newnode->next=start;
start=newnode;
}
}
void insert_at_end()
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the data to insert at end: ");
scanf("%d",&newnode->data);
newnode->next=NULL;
if(start==NULL)
{
start=newnode;
temp=newnode;
}
else
{
temp = start;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = newnode;
}
}
void insert_mid()
{
int key;
newnode=(struct node *)malloc(sizeof(struct node));
printf("\n Enter the data to insert at middle: ");
scanf("%d",&newnode->data);
if(start==NULL)
start=newnode;
else
{
printf("\n Enter the element after which you want to insert: ");
scanf("%d",&key);
temp=start;
while(temp->next!=NULL)
{
if(temp->data==key)
{
newnode->next=temp->next;
temp->next=newnode;
return;
}
temp=temp->next;
}
printf("Not Found");
}
}
void insert_mid1()
{
int pos,i,count=0;

temp=start;
while(temp!=NULL)
{
count++;
temp=temp->next;
}
printf("%d",count);

newnode=(struct node *)malloc(sizeof(struct node));


printf("\n Enter the data to insert at middle: ");
scanf("%d",&newnode->data);

if(start==NULL)
start=newnode;
else
{
printf("\n Enter the position to insert ");
scanf("%d",&pos);
temp=start;
if(pos>=count)
{
printf("\n Invalid Position");
}
else
{
for(i=2;i<pos-1;i++)
{
temp=temp->next;
}
newnode->next=temp->next;
temp->next=newnode;
}
}
}
void del_at_beg()
{
//temp=start;
start=start->next;
//free(temp);
}
void del_at_mid()
{
int key;
printf("\n Enter element to delete..");
scanf("%d",&key);
temp=start;
while(temp!=NULL)
{
if(temp->data==key) /Element deleted in between/
{
p->next=temp->next;
}
p=temp;
temp=temp->next;
}
display();
}
void del_at_end()
{
temp=start;
while(temp->next->next!= NULL)
{
temp=temp->next;
}
temp->next=NULL;
}
void search()
{
int flag = 0,search;
printf("\n Enter data to search:");
scanf("%d",&search);
temp = start;
while(temp!=NULL)
{
if(temp->data == search)
{
flag=1;
break;
}
temp=temp->next;
}
if(flag == 1)
printf("\n %d Element is Present in the List...",search);
else
printf("\n Not found..");
}
void count()
{
int length = 0;
temp = start;
while(temp!=NULL)
{
length++;
temp=temp->next;
}
printf("\n Length of Linked List : %d",length);
//return;
}
int main()
{
int choice;
printf("\n ***Singly Linear Linked list***\n");
do
{
printf("\n 1.Create \n 2.Display \n 3.Insert begin \n 4.Insert Last \n
5.Insert middle \n 6.Deletion at beg \n 7.Deletion at middle \n 8.Deletion at
end\n 9.Search \n 10.Number of nodes \n 11.Exit \n");

printf("\n Enter ur Choice:");


scanf("%d",&choice);

switch(choice)
{
case 1: create(); break;
case 2: display(); break;
case 3: insert_at_beg(); break;
case 4: insert_at_end(); break;
case 5: insert_mid(); break;
case 6: del_at_beg(); break;
case 7: del_at_mid(); break;
case 8: del_at_end(); break;
case 9: search(); break;
case 10: count(); break;
case 11: exit(0);
}
}while(choice<12);
}

Doubly Linked List:(Insert at end Delete at begin) :

#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
struct Node *prev;
} Node;
Node *insertAtEnd(Node *head, int value) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
if (head == NULL) {
newNode->prev = NULL;
return newNode;
}
Node *current = head;
while (current->next != NULL)
current = current->next;
current->next = newNode;
newNode->prev = current;
return head;
}
Node *deleteAtBegin(Node *head) {
if (head == NULL) {
printf("List is empty.\n");
return NULL;
}
Node *temp = head;
head = head->next;
if (head != NULL)
head->prev = NULL;
free(temp);
return head;
}
void displayList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node *head = NULL;
head = insertAtEnd(head, 10);
head = insertAtEnd(head, 20);
head = insertAtEnd(head, 30);
printf("Original List: ");
displayList(head);
head = deleteAtBegin(head);
printf("List after deleting from the beginning: ");
displayList(head);
return 0;
}
// Example usage:
// Node *head = NULL;
// head = insertAtEnd(head, 10);
// head = insertAtEnd(head, 20);
// head = insertAtEnd(head, 30);
// head = deleteAtBegin(head);

***THE END***

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy