0% found this document useful (0 votes)
13 views27 pages

Important Programs of DSA

The document outlines various algorithms and their implementations in C, including binary search (both iterative and recursive), linear search (iterative and recursive), bubble sort, factorial calculation (iterative and recursive), Fibonacci series (both recursive and iterative), selection sort, finding the maximum number in an array, polynomial multiplication, and double hashing. Each section includes code snippets demonstrating how to implement these algorithms. The document serves as a comprehensive guide for understanding and applying fundamental algorithms in programming.

Uploaded by

Himashree N R
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)
13 views27 pages

Important Programs of DSA

The document outlines various algorithms and their implementations in C, including binary search (both iterative and recursive), linear search (iterative and recursive), bubble sort, factorial calculation (iterative and recursive), Fibonacci series (both recursive and iterative), selection sort, finding the maximum number in an array, polynomial multiplication, and double hashing. Each section includes code snippets demonstrating how to implement these algorithms. The document serves as a comprehensive guide for understanding and applying fundamental algorithms in programming.

Uploaded by

Himashree N R
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/ 27

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Design and Analysis of Algorithms


2023-24

Himashree N R 1RV22CS069 4B
1. Binary search(iterative method)-
2. // Binary Search in C
3.
4. #include <stdio.h>
5.
6. int binarySearch(int array[], int x, int low, int high) {
7. // Repeat until the pointers low and high meet each other
8. while (low <= high) {
9. int mid = low + (high - low) / 2;
10.
11. if (array[mid] == x)
12. return mid;
13.
14. if (array[mid] < x)
15. low = mid + 1;
16.
17. else
18. high = mid - 1;
19. }
20.
21. return -1;
22. }
23.
24. int main(void) {
25. int n,arr[10],i;
26. int x;
27. printf("\nEnter the size of the array:");
28. scanf("%d",&n);
29. printf("\nEnter the elements of the array\n");
30. for(i=0;i<n;i++)
31. scanf("%d",&arr[i]);
32. printf("\nEnter the number to be searched:");
33. scanf("%d",&x);
34. int result = binarySearch(arr, x, 0, n - 1);
35. if (result == -1)
36. printf("\nElement not found\n");
37. else
38. printf("\nElement found at position %d\n", result + 1);
39. return 0;
40.
41. }
Binary search in recursive method-

// Binary Search in C

#include <stdio.h>

int binarySearch(int array[], int x, int low, int high) {


if (high >= low) {
int mid = low + (high - low) / 2;

// If found at mid, then return it


if (array[mid] == x)
return mid;

// Search the left half


if (array[mid] > x)
return binarySearch(array, x, low, mid - 1);

// Search the right half


return binarySearch(array, x, mid + 1, high);
}

return -1;
}

int main(void) {
int n,arr[10],i;
int x;
printf("\nEnter the size of the array:");
scanf("%d",&n);
printf("\nEnter the elements of the array\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("\nEnter the number to be searched:");
scanf("%d",&x);
int result = binarySearch(arr, x, 0, n - 1);
if (result == -1)
printf("\nElement not found\n");
else
printf("\nElement found at position %d\n", result + 1);
return 0;

}
2. LINEAR SEARCH(iterative method)-

// Linear Search in C

#include <stdio.h>

int search(int array[], int n, int x) {

// Going through array sequencially


for (int i = 0; i < n; i++)
if (array[i] == x)
return i;
return -1;
}

int main() {
int n,arr[10],i;
printf("\nEnter the value of n");
scanf("%d",&n);
printf("\nEnter the array elements");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("\nEnter the element to be searched");
int x;
scanf("%d",&x);
int result = search(arr, n, x);
if (result == -1)
printf("\nElement not found");
else
printf("\nElement found at index %d", result);
return 0;
}
Linear Search(recursive method)-

// C Program to implement linear search using recursion


#include <stdio.h>

// Function to perform linear search


int linearSearch(int* arr, int size, int key)
{
// if there are no elements, return -1
if (size == 0)
return -1;

// if the element at (size - 1) index is equal to key,


// return (size - 1)
if (arr[size - 1] == key) {
return size - 1;
}

// if not, call linear seach for same array arr but


// reducing the size by a single element
return linearSearch(arr, size - 1, key);
}

// Driver code
int main()
{
int n,arr[10],i;
printf("\nEnter the value of n");
scanf("%d",&n);
printf("\nEnter the array elements");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("\nEnter the element to be searched");
int x;
scanf("%d",&x);
int result = linearSearch(arr, n, x);
if (result == -1)
printf("\nElement not found");
else
printf("\nElement found at index %d", result);
return 0;

}
3. Bubble Sort-

// C program for implementation of Bubble sort


#include <stdio.h>

// Swap function
void swap(int* arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

// A function to implement bubble sort


void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n - 1; i++)

// Last i elements are already


// in place
for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr, j, j + 1);
}

// Function to print an array


void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver code
int main()
{
int n,arr[10],i;
printf("Enter the size of the array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\nSorted array is");
bubbleSort(arr, n);
printArray(arr, n);
return 0;
}

4. Factorial in iterative method-

// C program to implement the above approach


#include <stdio.h>

// Function to find factorial of given number


unsigned int factorial(unsigned int n)
{
int result = 1, i;

// loop from 2 to n to get the factorial


for (i = 2; i <= n; i++) {
result *= i;
}

return result;
}

// Driver code
int main()
{
int n;
printf("\nEnter the value of n:");
scanf("%d",&n);
printf("\nThe factorial of %d is %d", n, factorial(n));
return 0;
}

Factorial using recursive method-

// C program to find factorial of given number


#include <stdio.h>

// Function to find factorial of given number


unsigned int factorial(unsigned int n)
{
if (n == 1) {
return 1;
}
return n * factorial(n - 1);
}

// Driver code
int main()
{
int n;
printf("\nEnter the value of n:");
scanf("%d",&n);
printf("\nThe factorial of %d is %d", n, factorial(n));
return 0;
}

5. Fibonacci using recursive method-

// C Program to print the Fibonacci series using recursion


#include <stdio.h>

// first two values


int prev1 = 1;
int prev2 = 0;

// recursive function to print the fibonacci series


void fib(int n)
{
if (n < 3) {
return;
}
int fn = prev1 + prev2;
prev2 = prev1;
prev1 = fn;
printf("%d ", fn);
return fib(n - 1);
}

// function that handles the first two terms and calls the
// recursive function
void printFib(int n)
{
// when the number of terms is less than 1
if (n < 1) {
printf("Invalid number of terms\n");
}
// when the number of terms is 1
else if (n == 1) {
printf("%d ", 0);
}
// when the number of terms is 2
else if (n == 2) {
printf("%d %d", 0, 1);
}
// number of terms greater than 2
else {
printf("%d %d ", 0, 1);
fib(n);
}
return;
}

// driver code
int main()
{
int n;
printf("\nEnter the value of n:");
scanf("%d", &n);
printFib(n);
return 0;
}

Fibonacci series using iteration-

// C Program to print the fibonacci series using iteration


// (loops)
#include <stdio.h>

// function to print fibonacci series


void printFib(int n)
{
if (n < 1) {
printf("Invalid Number of terms\n");
return;
}

// when number of terms is greater than 0


int prev1 = 1;
int prev2 = 0;

// for loop to print fibonacci series


for (int i = 1; i <= n; i++) {
if (i > 2) {
int num = prev1 + prev2;
prev2 = prev1;
prev1 = num;
printf("%d ", num);
}

// for first two terms


if (i == 1) {
printf("%d ", prev2);
}
if (i == 2) {
printf("%d ", prev1);
}
}
}

// driver code
int main()
{

int n;
printf("\nEnter the value of n:");
scanf("%d", &n);
printFib(n);
return 0;

6. Selection Sort-

// C program for implementation of selection sort


#include <stdio.h>

void swap(int* xp, int* yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of unsorted subarray


for (i = 0; i < n - 1; i++) {
// Find the minimum element in unsorted array
min_idx = i;
for (j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first
// element
swap(&arr[min_idx], &arr[i]);
}
}

/* Function to print an array */


void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int n,i,arr[20];
printf("\nEnter the value of n:");
scanf("%d",&n);
printf("\nEnter the array elements");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
selectionSort(arr,n);
printf("\nSorted array is");
printArray(arr,n);
return 0;
}

7. Finding the maximum number in the array-

#include <stdio.h>
int main() {
int n;
double arr[100];
printf("Enter the number of elements (1 to 100): ");
scanf("%d", &n);

for (int i = 0; i < n; ++i) {


printf("Enter number%d: ", i + 1);
scanf("%lf", &arr[i]);
}

// storing the largest number to arr[0]


for (int i = 1; i < n; ++i) {
if (arr[0] < arr[i]) {
arr[0] = arr[i];
}
}

printf("Largest element = %.2lf", arr[0]);

return 0;
}

8. Polynomial Multiplication-

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct node
{
int coeff;
int exp;
struct node *next;
};
struct node *insert(struct node *head,int co,int ex)
{
struct node *temp;
struct node *new=(struct node *)malloc(sizeof(struct node));
new->coeff=co;
new->exp=ex;
new->next=NULL;
if(head==NULL || ex>head->exp)
{
new->next=head;
head=new;

}
else{
temp=head;
while(temp->next!=NULL && temp->next->exp!=ex)
{
temp=temp->next;

}
new->next=temp->next;
temp->next=new;
}
return head;
}
struct node *create(struct node *head)
{
int n,i;
int coeff,exp;
printf("\nEnter the number of terms in the polynomial:");
scanf("%d",&n);
for(i=0;i<=n-1;i++)
{
printf("\nEnter the coefficient for the term %d",i+1);
scanf("%d",&coeff);
printf("\nEnter the exponent for the term %d",i+1);
scanf("%d",&exp);
head=insert(head,coeff,exp);
}
return head;
}
void print(struct node *head)
{
struct node *temp;
temp=head;
while(temp->next!=NULL)
{
printf("\n%dx^%d+",temp->coeff,temp->exp);
temp=temp->next;
}
printf("\n%dx^%d+",temp->coeff,temp->exp);
}
void multi(struct node *head1,struct node *head2)
{

struct node *ptr1=head1;


struct node *ptr2=head2;
struct node *head3=NULL;
if(head1==NULL || head2==NULL)
{
printf("\nZero Polynomial");
return;
}
while(ptr1!=NULL)
{
while(ptr2!=NULL)
{
head3=insert(head3,ptr1->coeff*ptr2->coeff,ptr1->exp+ptr2->exp);
ptr2=ptr2->next;
}
ptr1=ptr1->next;
ptr2=head2;
}
print(head3);
}
int main()
{
struct node *head1=NULL;
struct node *head2=NULL;
printf("\nEnter the first polynomial");
head1=create(head1);
printf("\nEnter the second polynomial");
head2=create(head2);
multi(head1,head2);
return 0;
}

9. Double hashing-

#include <stdio.h>
#include <stdlib.h>
#define TABLE_SIZE 10
int h[TABLE_SIZE]={NULL};
void insert()
{
int i,h1,h2,key,index,flag=0;
printf("\nEnter the key to be inserted:");
scanf("%d",&key);
h1=key%TABLE_SIZE;
h2=7-(key%7);
for(i=0;i<TABLE_SIZE;i++)
{
index=(h1=i*h2)%TABLE_SIZE;
if(h[index]==NULL)
{
h[index]=key;
break;
}
}
if(i==TABLE_SIZE)
{
printf("\nValue cannot be inserted");
}
}
void search()
{
int i,index,h1,h2,key,flag=0;
printf("\nEnter the key to be searched:");
scanf("%d",&key);
h1=key%TABLE_SIZE;
h2=7-(key%7);
for(i=0;i<TABLE_SIZE;i++)
{
index=(h1+i*h2)%TABLE_SIZE;
if(h[index]==key)
{
printf("\nKey found at index %d",index);
}
}
if(i==TABLE_SIZE)
{
printf("\nValue doesn't found");
}
}
void display()
{
int i;
printf("\nElements of the hash table are\n");
for(i=0;i<TABLE_SIZE;i++)
{
printf("%d found at the position %d",h[i],i);
}
}
main()
{
int opt,i;
while(1)
{
printf("\nPress 1.Insert\t2.Search\t3.Display\t4.Exit\n");
printf("\nEnter the option:");
scanf("%d",&opt);
switch(opt)
{
case 1:
{
insert();
break;
}
case 2:
{
seach();
break;
}
case 3:
{
display();
break;
}
case 4:
exit(0);
}
}
}

10. Hashing using Linear Probing-

#include<stdio.h>
#define max 10

int hash(int HT[ ], int key)


{
return ( key%10);
}

void display(int HT[])


{
int i;
printf("HASH TABLE : \n");
for(i=0;i<max;i++)
printf("\n%d->%d", i, HT[i]);
}

void insert_LinerProbing(int HT[ ],int key)


{
int index,i;
index = hash(HT,key);
if(HT[index] ==-1)
{
HT[index] =key;
printf("\nSuccesful Insertion");
return;
}

// Linerly serach for the array index+1 to max-1 or 0 to index-1


for(i=index+1; i<max;i++)
{
if(HT[i] == -1)
{
HT[i] =key;
printf("\nSuccesful Insertion");
return;
}
}

for(i=0;i<index ;i++)
{
if(HT[i] == -1)
{
HT[i] =key;
printf("\nSuccesful Insertion");
return;
}
}

printf("\nUnsuccessful Insertion : Hash Table is FULL");


}
void Delete_LinerProbing(int HT[ ],int key)
{
int index,i;
index = hash(HT,key);
if(HT[index] ==key)
{
HT[index] =-1;
printf("\nSuccesful Deletion");
return;
}

// Linerly serach for the array index+1 to max-1 or 0 to index-1


for(i=index+1; i<max;i++)
{
if(HT[i] == key)
{
HT[i] =-1;
printf("\nSuccesful Deletion");
return;
}
}

for(i=0;i<index ;i++)
{
if(HT[i] == key)
{
HT[i] =-1;
printf("\nSuccesful Deletion");
return;
}
}

printf("\nUnsuccessful Deletion: Key Not Found");


}
void main()
{
int HT[max]; // hash table
int key,i,choice;
printf("\n hash table\n");
for(i=0;i<max;i++)
HT[i] = -1;

while(1)
{
printf("\nEnter the choice \n1 : insert \n2 : delete\n3 : display\n4
: exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\nEnter the key to be inerted :");
scanf("%d",&key);
insert_LinerProbing(HT,key);
break;
case 2: printf("\nEnter the key to be inerted :");
scanf("%d",&key);
Delete_LinerProbing(HT,key);
break;
case 3: display(HT);
break;
default:exit(0);
}

11. Heapsort-

#include<stdio.h>
#include<stdlib.h>
#include<math.h>

//Bottom Up Heap Creation


void heapify(int a[],int n)
{

int heap=0,j,key,k,i;
for (i=n/2;i>=1;i--)
{
k=i;
key=a[i]; // v is the key value
heap=0;
while (!heap && 2*k<=n)
{

j=2*k;
if (j<n)
{
if (a[j]<a[j+1])
j=j+1;
}

if (key>=a[j])
heap=1; // heapification ends
else
{
a[k]=a[j]; // shift a[j] up ie to parents position
k=j;
}
}//end of while
a[k]=key;
}//end of for
}

void HeapSort(int a[],int n)


{
int i,t;

//Intial Heap
heapify(a,n);
// sorting logic
for (i=n; i>1 ;i--) //uxing max deletion logic
{
t=a[i];
a[i]=a[1];
a[1]=t;
heapify(a,i-1);
}
}

int main()
{
int a[100],n,i;
printf("Enter no. of elements:");
scanf("%d",&n);
printf("\nEnter %d elements:\n",n);
for (i=1;i<=n;i++)
scanf("%d",&a[i]);
HeapSort(a,n);
printf("\nSorted array is \n\n");
for (i=1;i<=n;i++)
printf("%d ",a[i]);
return 0;
}

12. Binary Search Tree creation and traversal

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/* BST node */

struct node
{
int data;
struct node *left_child;
struct node *right_child;
};

typedef struct node* NODE;

/* Function to create a newnode */


NODE getnode()
{
NODE p;
p = (NODE) malloc(sizeof(struct node));
if(p== NULL)
{
printf("Insufficient Memory");
exit(0);
}
p->left_child= NULL;
p->right_child = NULL;
return p;
}
//InOrder Succucessor of a node p
int InOrderSucc(NODE p)
{
NODE q;
if(p == NULL)
{
printf(" ERROR!!!!!!!!!!!!");
exit(0);
}
q= p->right_child; // one step right
// travrse left
while(q->left_child != NULL)
q=q->left_child;
return q->data;
}

NODE BSTInsert(NODE root, int x)


{
NODE p,q,parent ;

q= getnode();
q->data =x;

if(root == NULL)
return q;
p= root;
while(p !=NULL)
{
parent = p;
if(x == p->data )
{
printf("Duplicate Entry");
free(q);
return root;
}
if( x < p->data)
p=p->left_child;
else
p=p->right_child;
}
if(x < parent->data)
parent->left_child = q;
else
parent->right_child = q;
return root;
}
NODE BSTDelete(NODE tp, int x)
{
int y;
NODE r;
if (tp == NULL)
{
printf(" Element %d Not Presenst",x);
return NULL; //tp
}
if(x == tp->data )
{
//Case 1
if( tp->left_child == NULL && tp->right_child==NULL)
{
free(tp);
return NULL;
}
//Case 2 : left subtree is NULL
if(tp->left_child == NULL)
{
r= tp->right_child;
free(tp);
return r;
}
//Case 2 : right subtree is NULL
if(tp->right_child == NULL)
{
r= tp->left_child;
free(tp);
return r;
}
// Case 3: both left && right NOT NULL
y = InOrderSucc(tp);
tp->data= y;
tp->right_child= BSTDelete(tp->right_child,y);
return tp;
}
if( x < tp->data)
tp->left_child = BSTDelete(tp->left_child,x);
else
tp->right_child = BSTDelete(tp->right_child,x);
return tp;
}
void InOrder( NODE p)
{
if( p ) // p != NULL
{
InOrder(p->left_child);
printf("%d\t ",p->data);
InOrder(p->right_child);
}
}
void PreOrder( NODE p)
{
if( p != NULL)
{
printf("%d\t",p->data);
PreOrder(p->left_child);

PreOrder(p->right_child);
}
}
void PostOrder( NODE p)
{
if( p)
{
PostOrder(p->left_child);
PostOrder(p->right_child);
printf("%d\t",p->data);
}
}

int main()
{

int choice,x;
NODE root=NULL;

printf("Demonstration of BST Insert ,Delete, Display");


while(1)
{

printf("\n1:Inser\n2:Delette\n3:Inorder Display\n4:Preorder
Display\n5:Postorder Display\n6:exit ");
printf("\nEnter the Choice :");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("\nEnter the element to be Inserted ");
scanf("%d",&x);
root=BSTInsert(root,x);
break;
case 2:printf("\nEnter the element to be Deteted ");
scanf("%d",&x);
root=BSTDelete(root,x);
break;
case 3 :printf("\nTraversal of BST : Inorder");
InOrder(root);
break;
case 4 :printf("\nTraversal of BST : Preorder");
PreOrder(root);
break;
case 5 :printf("\nTraversal of BST : Postorder");
PostOrder(root);
break;

case 6:exit(0);

} //switch
}//while
return 0;
}//main

13. Stack Operations using array-

#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}

}
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");

}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}
}

14. Queue operations using Array-

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

You might also like