You are on page 1of 102

MAHARISHI DAYANAND

UNIVERSITY

AKIDO COLLEGE OF
ENGINEERING PRACTICAL FILE
B Tech CSE
DATA STRUCTURE AND ALGORITHM

SUBMITTED BY:
AARYAVART
VIRAT
BHUSHAN
REGISTRATION NUMBER : 2113071058
2113071230
INDEX:
S.no. Topic Date Teacher’s
Sign
01 Write a menu driven program that 30-09-22
implements following operations (using
separate functions) on a linear array:
Insert a new element at end as well as
at a given position
 Delete an element from a given
whose value is given or whose position
is given
 To find the location of a given
element
 To display the elements of the linear
array
02 Write a menu driven program that 07-10-22
maintains a linear linked list whose
elements are stored in on ascending
order and implements the following
operations (using separate functions):
 Insert a new element
 Delete an existing element
 Search an element
 Display all the element
03 Write a program to demonstrate the 14-10-22
use of stack (implemented using linear
array) in converting arithmetic
expression from infix notation to postfix
notation.
04 Program to demonstrate the use of 22-10-22
stack (implemented using linear linked
lists) in evaluating arithmetic expression
in postfix notation
05 Program to demonstration the 28-10-22
implementation of various operations
on a linear queue represented using a
linear array

06 Program to demonstration the 05-11-22


implementation of various operations
on a circular queue represented using a
linear array.
07 Program to demonstration the 28-10-22
implementation of various operations
on a queue represented using a linear
linked list (linked queue).
08 Program to illustrate the 28-10-22
implementation of different operations
on a binary search tree.
09 Program to illustrate the traversal of 05-11-22
graph using breadth-first search
10 Program to illustrate the traversal of 05-11-22
graph using depth-first search.
11 Program to sort an array of integers in 12-11-22
ascending order using bubble sort
12 Program to sort an array of integers in 12-11-22
ascending order using selection sort.
13 Program to sort an array of integers in 19-11-22
ascending order using insertion sort.
14 Program to sort an array of integers in 26-11-22
ascending order using radix sort.
15 Program to sort an array of integers in 26-11-22
ascending order using merge sort.
16 Program to sort an array of integers in 03-12-22
ascending order using quick sort.
17 Program to sort an array of integers in 03-12-22
ascending order using heap sort.
18 Program to sort an array of integers in 03-12-22
ascending order using shell sort.
19 Program to demonstrate the use of 10-12-22
linear search to search a given element
in an array.
20 Program to demonstrate the use of 10-12-22
binary search to search a given element
in a sorted array in ascending order.
PROGRAM 1

Write a menu driven program that implements following operations (using separate functions) on a
linear array:

Insert a new element at end as well as at a given position

 Delete an element from a given whose value is given or whose position is given

 To find the location of a given element

 To display the elements of the linear array

#include<stdio.h>

#include<stdlib.h>

int a[10], pos, elem;

int n = 0;

void create();

void display();

void insert();

void del();

int main()

int choice;

while(1)

printf("\n\n~~~~MENU~~~~");

printf("\n=>1. Create an array of N integers");

printf("\n=>2. Display of array elements"); printf("\

n=>3. Insert elem at a given pos"); printf("\n=>4.

Delete an element at a given pos"); printf("\n=>5.

Exit");

printf("\nEnter your choice: ");

scanf("%d", &choice);

switch(choice)
{

case 1: create();

break;

case 2: display();

break;

case 3: insert();

break ;

case 4: del();

break;

case 6: exit(1);

break;

default: printf("\nPlease enter a valid choice:");

}}

void create(){

int i;

printf("\nEnter the number of elements: ");

scanf("%d", &n);

printf("\nEnter the elements: ");

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

scanf("%d", &a[i]);

void display()

{ int i;

if(n == 0)

printf("\nNo elements to display");

return;

printf("\nArray elements are: ");

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

printf("%d\t ", a[i]);


}

void insert(){ int i;

if(n == 5)

printf("\nArray is full. Insertion is not possible");

return;

do{

printf("\nEnter a valid position where element to be inserted: ");

scanf("%d", &pos);

}while(pos > n);

printf("\nEnter the value to be inserted: ");

scanf("%d", &elem);

for(i=n-1; i>=pos ; i--)

a[i+1] = a[i];

a[pos] = elem;

n = n+1;

display();

void del()

Int I;

if(n == 0)

printf("\nArray is empty and no elements to delete");

return;

do { printf("\nEnter a valid position from where element to be deleted: ");

scanf("%d", &pos);}

while(pos>=n);

elem = a[pos];

printf("\nDeleted element is : %d \n", elem);


for( i = pos; i< n-1; i++)

{ a[i] = a[i+1];

n = n-1;

display();

}
OUTPUT
COMPLEXITY

1- >Best case = if we get the element at the index 0 then is time complexity will be constant which is
order of 1 [O(1)].

2- >Worst case = if the element is in the last position then its time complexity will be order of n[O(n)],
Because in the linear search, the searching starts from the index 0 to n.

If we did not get the element in the array but the searching reached the end position still its time
complexity will be O(n).

3- >Average case = In the average case, we consider a mid value and the we will do (1+n)/2, if the
value of n reached infinity, then infinity/2 will be infinity only because we ignore the small value, but
still, there will be order on n[O(n)] in the average case.
PROGRAM 2
Write a menu driven program that maintains a linear linked list whose elements are stored in on
ascending order and implements the following operations (using separate functions):

 Insert a new element

 Delete an existing element

 Search an element

 Display all the element

/*

* C++ Program to Implement Singly Linked List

*/

#include<iostream>

#include<cstdio>

#include<cstdlib>

using namespace std;

/*

* Node Declaration

*/

struct node

int info;

struct node *next;

}*start;

/*

* Class Declaration

*/

class single_llist

public:

node* create_node(int);

void insert_begin();

void insert_pos();

void insert_last();
void delete_pos();

void search();

void update();

void display();

single_llist()

start = NULL;

};

/*

* Main :contains menu

*/

main()

int choice, nodes, element, position, i;

single_llist sl;

start = NULL;

while (1)

cout<<endl<<" "<<endl;

cout<<endl<<"Operations on singly linked

list"<<endl; cout<<endl<<" "<<endl;

cout<<"1.Insert Node at beginning"<<endl;

cout<<"2.Insert node at last"<<endl;

cout<<"3.Insert node at position"<<endl;

cout<<"5.Delete a Particular Node"<<endl;

cout<<"6.Update Node Value"<<endl;

cout<<"7.Search Element"<<endl;

cout<<"8.Display Linked List"<<endl;

cout<<"10.Exit "<<endl;

cout<<"Enter your choice : ";

cin>>choice;

switch(choice)

case 1:
cout<<"Inserting Node at Beginning: "<<endl;

sl.insert_begin();

cout<<endl;

break;

case 2:

cout<<"Inserting Node at Last: "<<endl;

sl.insert_last();

cout<<endl;

break;

case 3:

cout<<"Inserting Node at a given position:"<<endl;

sl.insert_pos();

cout<<endl;

break;

case 4:

cout<<"Sort Link List: "<<endl;

sl.sort();

cout<<endl;

break;

case 5:

cout<<"Delete a particular node: "<<endl;

sl.delete_pos();

break;

case 6:

cout<<"Update Node Value:"<<endl;

sl.update();

cout<<endl;

break;

case 7:

cout<<"Search element in Link List: "<<endl;

sl.search();

cout<<endl;

break;

case 8:

cout<<"Display elements of link list"<<endl;

sl.display();
cout<<endl;

break;

case 9:

cout<<"Reverse elements of Link List"<<endl;

sl.reverse();

cout<<endl;

break;

case 10:

cout<<"Exiting..."<<endl;

exit(1);

break;

default:

cout<<"Wrong choice"<<endl;

/*

* Creating Node

*/

node *single_llist::create_node(int value)

struct node *temp, *s;

temp = new(struct node);

if (temp == NULL)

cout<<"Memory not allocated "<<endl;

return 0;

else

temp->info = value;

temp->next = NULL;

return temp;

}
/*

* Inserting element in beginning

*/

void single_llist::insert_begin()

int value;

cout<<"Enter the value to be inserted: ";

cin>>value;

struct node *temp, *p;

temp = create_node(value);

if (start == NULL)

start = temp;

start->next = NULL;

else

p = start;

start = temp;

start->next = p;

cout<<"Element Inserted at beginning"<<endl;

/*

* Inserting Node at last

*/

void single_llist::insert_last()

int value;

cout<<"Enter the value to be inserted: ";

cin>>value;

struct node *temp, *s;

temp = create_node(value);

s = start;
while (s->next != NULL)

s = s->next;

temp->next = NULL;

s->next = temp;

cout<<"Element Inserted at last"<<endl;

/*

* Insertion of node at a given position

*/

void single_llist::insert_pos()

int value, pos, counter = 0;

cout<<"Enter the value to be inserted: ";

cin>>value;

struct node *temp, *s, *ptr;

temp = create_node(value);

cout<<"Enter the postion at which node to be inserted: ";

cin>>pos;

int i;

s = start;

while (s != NULL)

s = s->next;

counter++;

if (pos == 1)

if (start == NULL)

start = temp;

start->next = NULL;

else
{

ptr = start;

start = temp;

start->next = ptr;

else if (pos > 1 && pos <= counter)

s = start;

for (i = 1; i < pos; i++)

ptr = s;

s = s->next;

ptr->next = temp;

temp->next = s;

else

cout<<"Positon out of range"<<endl;

/*

* Delete element at a given position

*/

void single_llist::delete_pos()

int pos, i, counter = 0;

if (start == NULL)

cout<<"List is empty"<<endl;

return;

cout<<"Enter the position of value to be deleted: ";

cin>>pos;
struct node *s, *ptr;

s = start;

if (pos == 1)

start = s->next;

else

while (s != NULL)

s = s->next;

counter++;

if (pos > 0 && pos <= counter)

s = start;

for (i = 1;i < pos;i++)

ptr = s;

s = s->next;

ptr->next = s->next;

else

cout<<"Position out of range"<<endl;

free(s);

cout<<"Element Deleted"<<endl;

/*

* Searching an element

*/

void single_llist::search()

{
int value, pos = 0;

bool flag = false;

if (start == NULL)

cout<<"List is empty"<<endl;

return;

cout<<"Enter the value to be searched: ";

cin>>value;

struct node *s;

s = start;

while (s != NULL)

pos++;

if (s->info == value)

flag = true;

cout<<"Element "<<value<<" is found at position "<<pos<<endl;

s = s->next;

if (!flag)

cout<<"Element "<<value<<" not found in the list"<<endl;

/*

* Display Elements of a link list

*/

void single_llist::display()

struct node *temp;

if (start == NULL)

cout<<"The List is Empty"<<endl;

return;

temp = start;
cout<<"Elements of list are: "<<endl;

while (temp != NULL)

cout<<temp->info<<"->";

temp = temp->next;

cout<<"NULL"<<endl;

}
OUTPUT
COMPLEXITY
In a singly linked list, the time complexity for inserting and deleting an
element from the list is O(n).
PROGRAM 3
 Write a program to demonstrate the use of stack (implemented using linear array) in
converting arithmetic expression from infix notation to postfix notation.

#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1;
void push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >=
priority(*e)) printf("%c ",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}return 0;
}
OUTPUT
COMPLEXITY

O(N), where N is the size of the infix expression


PROGRAM 4
 Program to demonstrate the use of stack (implemented using linear linked lists) in
evaluating arithmetic expression in postfix notation

// C program to evaluate value of a postfix expression


#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

// Stack type
struct Stack
{
int top;
unsigned capacity;
int* array;
};

// Stack Operations
struct Stack* createStack( unsigned capacity )
{
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));

if (!stack) return NULL;

stack->top = -1;
stack->capacity = capacity;
stack->array = (int*) malloc(stack->capacity * sizeof(int));

if (!stack->array) return NULL;

return stack;
}

int isEmpty(struct Stack* stack)


{
return stack->top == -1 ;
}

char peek(struct Stack* stack)


{
return stack->array[stack->top];
}

char pop(struct Stack* stack)


{
if (!isEmpty(stack))
return stack->array[stack->top--] ;
return '$';
}

void push(struct Stack* stack, char op)


{
stack->array[++stack->top] = op;
}

// The main function that returns value of a given postfix expression


int evaluatePostfix(char* exp)
{
// Create a stack of capacity equal to expression size
struct Stack* stack = createStack(strlen(exp));
int i;

// See if stack was created successfully


if (!stack) return -1;

// Scan all characters one by one


for (i = 0; exp[i]; ++i)
{
// If the scanned character is an operand (number here),
// push it to the stack.
if (isdigit(exp[i]))
push(stack, exp[i] - '0');

// If the scanned character is an operator, pop two


// elements from stack apply the operator
else
{
int val1 = pop(stack);
int val2 = pop(stack);
switch (exp[i])
{
case '+': push(stack, val2 + val1); break;
case '-': push(stack, val2 - val1); break;
case '*': push(stack, val2 * val1); break;
case '/': push(stack, val2/val1); break;
}
}
}
return pop(stack);
}

// Driver program to test above functions


int main()
{
char exp[] = "231*+9-";
printf ("postfix evaluation: %d", evaluatePostfix(exp));
return 0;
}
OUTPUT
COMPLEXITY

The time complexity here is O(N)


PROGRAM 5
 Program to demonstration the implementation of various operations on a linear queue
represented using a linear 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;

default:

printf("Wrong Choice: please see the options");

return 0;

}
OUTPUT
COMPLEXITY

The time complexity here is O(N)


PROGRAM 6
 Program to demonstration the implementation of various operations on a circular queue
represented using a linear array.

#include <stdio.h>

# define max 6

int queue[max]; // array declaration

int front=-1;

int rear=-1;

// function to insert an element in a circular queue

void enqueue(int element)

if(front==-1 && rear==-1) // condition to check queue is empty

front=0;

rear=0;

queue[rear]=element;

else if((rear+1)%max==front) // condition to check queue is full

printf("Queue is overflow..");

else

rear=(rear+1)%max; // rear is incremented

queue[rear]=element; // assigning a value to the queue at the rear position.

// function to delete the element from the queue

int dequeue()
{

if((front==-1) && (rear==-1)) // condition to check queue is empty

printf("\nQueue is underflow..");

else if(front==rear)

printf("\nThe dequeued element is %d", queue[front]);

front=-1;

rear=-1;

else

printf("\nThe dequeued element is %d", queue[front]);

front=(front+1)%max;

// function to display the elements of a queue

void display()

int i=front;

if(front==-1 && rear==-1)

printf("\n Queue is empty..");

else

printf("\nElements in a Queue are :");

while(i<=rear)

printf("%d,", queue[i]);
i=(i+1)%max;

int main()

int choice=1,x; // variables declaration

while(choice<4 && choice!=0) // while loop

printf("\n Press 1: Insert an element");

printf("\nPress 2: Delete an element");

printf("\nPress 3: Display the element");

printf("\nEnter your choice");

scanf("%d", &choice);

switch(choice)

case 1:

printf("Enter the element which is to be inserted");

scanf("%d", &x);

enqueue(x);

break;

case 2:

dequeue();

break;

case 3:

display();

}}

return 0;

}
OUTPUT
COMPLEXITY
Time complexity of enQueue(), deQueue() operation is O(1) as there is no
loop in any of the operation.
PROGRAM 7

 Program to demonstration the implementation of various operations on a queue


represented using a linear linked list (linked queue).
#include <stdio.h>

#include

<stdlib.h>

struct node

int info;

struct node *ptr;

}*front,*rear,*temp,*front1;

int frontelement();

void enq(int data);

void deq();

void empty();

void display();

void create();

void

queuesize();

int count = 0;

int main()

int no, ch, e;

printf("\n 1 - Enque");

printf("\n 2 - Deque");

printf("\n 3 - Front element");

printf("\n 4 - Empty");

printf("\n 5 - Exit");

printf("\n 6 - Display");
printf("\n 7 - Queue

size"); create();

while (1)

printf("\n Enter choice :

"); scanf("%d", &ch);

switch (ch)

case 1:

printf("Enter data : ");

scanf("%d", &no);

enq(no);

break;

case 2:

deq();

break;

case 3:

e = frontelement();

if (e != 0)

printf("Front element : %d",

e); else

printf("\n No front element in Queue as queue is empty");

break;

case 4:

empty();

break;

case 5:

exit(0)

; case 6:

display()

; break;

case 7:

queuesize();

break;

default:
printf("Wrong choice, Please enter correct choice ");

break;

/* Create an empty queue */

void create()

front = rear = NULL;

/* Returns queue size */

void queuesize()

printf("\n Queue size : %d", count);

/* Enqueing the queue */

void enq(int data)

if (rear == NULL)

rear = (struct node *)malloc(1*sizeof(struct node));

rear->ptr = NULL;

rear->info = data;

front = rear;

else

temp=(struct node *)malloc(1*sizeof(struct node));

rear->ptr = temp;

temp->info =

data; temp->ptr =

NULL;
rear = temp;

count++;

/* Displaying the queue elements */

void display()

front1 = front;

if ((front1 == NULL) && (rear == NULL))

printf("Queue is empty");

return;

while (front1 != rear)

printf("%d ", front1-

>info); front1 = front1-

>ptr;

if (front1 == rear)

printf("%d", front1-

>info);

/* Dequeing the queue */

void deq()

front1 = front;

if (front1 == NULL)

printf("\n Error: Trying to display elements from empty

queue"); return;

else
if (front1->ptr != NULL)

front1 = front1->ptr;

printf("\n Dequed value : %d", front-

>info); free(front);

front = front1;

else

printf("\n Dequed value : %d", front-

>info); free(front);

front =

NULL; rear

= NULL;

count--;

/* Returns the front element of queue */

int frontelement()

if ((front != NULL) && (rear !=

NULL)) return(front->info);

else

return 0;

/* Display if queue is empty or not */

void empty()

if ((front == NULL) && (rear ==

NULL)) printf("\n Queue empty");

else

printf("Queue not empty");}


OUTPUT
COMPLEXITY
O(1), The time complexity of both operations enqueue() and dequeue() is
O(1) as it only changes a few pointers in both operations.
PROGRAM 8
 Program to illustrate the implementation of different operations on a binary search tree.
#include <stdio.h>

#include <stdlib.h>

struct node {

int key;

struct node *left, *right;

};

// Create a node

struct node *newNode(int item) {

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

temp->key = item;

temp->left = temp->right =

NULL; return temp;

// Inorder Traversal

void inorder(struct node *root) {

if (root != NULL) {

// Traverse left

inorder(root->left);

// Traverse root

printf("%d -> ", root-

>key);

// Traverse right

inorder(root->right);

// Insert a node
struct node *insert(struct node *node, int key) {

// Return a new node if the tree is empty

if (node == NULL) return

newNode(key);

// Traverse to the right place and insert the node

if (key < node->key)

node->left = insert(node->left,

key); else

node->right = insert(node->right, key);

return node;

// Find the inorder successor

struct node *minValueNode(struct node *node) {

struct node *current = node;

// Find the leftmost leaf

while (current && current->left !=

NULL) current = current->left;

return current;

// Deleting a node

struct node *deleteNode(struct node *root, int key) {

// Return if the tree is empty

if (root == NULL) return

root;

// Find the node to be deleted

if (key < root->key)

root->left = deleteNode(root->left, key);

else if (key > root->key)

root->right = deleteNode(root->right, key);


else {

// If the node is with only one child or no

child if (root->left == NULL) {

struct node *temp = root->right;

free(root);

return temp;

} else if (root->right == NULL)

{ struct node *temp = root-

>left; free(root);

return temp;

// If the node has two children

struct node *temp = minValueNode(root->right);

// Place the inorder successor in position of the node to be deleted

root->key = temp->key;

// Delete the inorder successor

root->right = deleteNode(root->right, temp->key);

return root;

// Driver code

int main() {

struct node *root =

NULL; root =

insert(root, 8); root =

insert(root, 3); root =

insert(root, 1); root =

insert(root, 6); root =

insert(root, 7); root =

insert(root, 10); root =

insert(root, 14); root =

insert(root, 4);
printf("Inorder traversal: ");

inorder(root);

printf("\nAfter deleting 10\n");

root = deleteNode(root, 10);

printf("Inorder traversal: ");

inorder(root);

}
OUTPUT
COMPLEXITY
The worst-case time complexity of search and insert operations is O(h)
where h is the height of the Binary Search Tree. In the worst case, we may
have to travel from root to the deepest leaf node. The height of a skewed
tree may become n and the time complexity of search and insert operation
may become O(n).
PROGRAM 9
 Program to illustrate the traversal of graph using breadth-first search
#include<stdio.h>

int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1;

void bfs(int v) {

for(i = 1; i <= n; i++)

if(a[v][i] && !

visited[i]) q[++r] = i;

if(f <= r) {

visited[q[f]] =

1;

bfs(q[f++]);

int main()

{ int v;

printf("\n Enter the number of vertices:");

scanf("%d", &n);

for(i=1; i <= n; i+

+) { q[i] = 0;

visited[i] = 0;

printf("\n Enter graph data in matrix form:\n");

for(i=1; i<=n; i++) {

for(j=1;j<=n;j++) {

scanf("%d", &a[i][j]);

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

scanf("%d", &v);
bfs(v);

printf("\n The node which are reachable are:\n");

for(i=1; i <= n; i+

+) { if(visited[i])

printf("%d\t", i);

else {

printf("\n Bfs is not possible. Not all nodes are

reachable"); break;

}
OUTPUT
COMPLEXITY

O(V+E), where V is the number of nodes and E is the number of edges.


PROGRAM 10
 Program to illustrate the traversal of graph using depth-first search.
#include<stdio.h>

void DFS(int);

int G[10][10],visited[10],n; //n is no of vertices and graph is sorted in array G[10][10]

int main()

int i,j;

printf("Enter number of vertices:");

scanf("%d",&n);

//read the adjecency matrix

printf("\nEnter adjecency matrix of the graph:");

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

for(j=0;j<n;j++)

scanf("%d",&G[i][j]);

//visited is initialized to zero

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

visited[i]=0;

DFS(0);

void DFS(int i)

int j; printf("\n

%d",i);

visited[i]=1;

for(j=0;j<n;j++)

if(!visited[j]&&G[i][j]==1)

DFS(j);

}
OUTPUT
COMPLEXITY

O(V + E), where V is the number of vertices and E is the number of edges in
the graph.
PROGRAM 11
 Program to sort an array of integers in ascending order using bubble sort
#include <stdio.h>

#define MAXSIZE 10

int main()

int array[MAXSIZE];

int i, j, num, temp;

printf("Enter the value of num \n");

scanf("%d", &num);

printf("Enter the elements one by one \n");

for (i = 0; i < num; i++)

scanf("%d", &array[i]);

printf("Input array is \n");

for (i = 0; i < num; i++)

printf("%d\n", array[i]);

/* Bubble sorting begins */

for (i = 0; i < num; i++)

for (j = 0; j < (num - i - 1); j++)

if (array[j] > array[j + 1])

temp = array[j];
array[j] = array[j + 1];

array[j + 1] = temp;

printf("Sorted array is...\n");

for (i = 0; i < num; i++)

printf("%d\n", array[i]);

}
OUTPUT
COMPLEXITY

Here the time complexity is O(N )


2
PROGRAM 12
 Program to sort an array of integers in ascending order using selection sort.
// Selection sort in C

#include <stdio.h>

// function to swap the the position of two elements

void swap(int *a, int *b) {

int temp = *a;

*a = *b;

*b = temp;

void selectionSort(int array[], int size) {

for (int step = 0; step < size - 1; step++) {

int min_idx = step;

for (int i = step + 1; i < size; i++) {

// To sort in descending order, change > to < in this line.

// Select the minimum element in each loop.

if (array[i] < array[min_idx])

min_idx = i;

// function to print an array

void printArray(int array[], in }

// put min at the correct position

swap(&array[min_idx], &array[step]);

t size) {

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

printf("%d ", array[i]);

}
printf("\n");

// driver code

int main() {

int data[] = {20, 12, 10, 15, 2};

int size = sizeof(data) / sizeof(data[0]);

selectionSort(data, size);

printf("Sorted array in Acsending Order:\n");

printArray(data, size);

}
OUTPUT
COMPLEXITY
Time Complexity: The time complexity of Selection Sort is O(N 2) as there
are two nested loops:
 One loop to select an element of Array one by one = O(N)
 Another loop to compare that element with every other Array element =
O(N)
Therefore overall complexity = O(N) * O(N) = O(N*N) = O(N 2)
PROGRAM 13
 Program to sort an array of integers in ascending order using insertion sort.
#include <stdio.h>

void insert(int a[], int n) /* function to sort an aay with insertion sort */

int i, j, temp;

for (i = 1; i < n; i++) {

temp = a[i];

j = i - 1;

while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one position ahead
from their current position*/

a[j+1] = a[j];

j = j-1;

a[j+1] = temp;

void printArr(int a[], int n) /* function to print the array */

int i;

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

printf("%d ", a[i]);

int main()

{
int a[] = { 12, 31, 25, 8, 32, 17 };

int n = sizeof(a) / sizeof(a[0]);

printf("Before sorting array elements are - \n");

printArr(a, n);

insert(a, n);

printf("\nAfter sorting array elements are - \n");

printArr(a, n);

return 0;

}
OUTPUT
COMPLEXITY

Here the time complexity is O(N^2)


PROGRAM 14
 Program to sort an array of integers in ascending order using radix sort.

// Radix Sort in C Programming

#include <stdio.h>

// Function to get the largest element from an array


int getMax(int array[], int n) {
int max = array[0];
for (int i = 1; i < n; i++)
if (array[i] > max)
max = array[i];
return max;
}

// Using counting sort to sort the elements in the basis of significant places
void countingSort(int array[], int size, int place) {
int output[size + 1];
int max = (array[0] / place) % 10;

for (int i = 1; i < size; i++) {


if (((array[i] / place) % 10) > max)
max = array[i];
}
int count[max + 1];

for (int i = 0; i < max; ++i)


count[i] = 0;
// Calculate count of elements
for (int i = 0; i < size; i++)
count[(array[i] / place) % 10]++;

// Calculate cumulative count


for (int i = 1; i < 10; i++)
count[i] += count[i - 1];

// Place the elements in sorted order


for (int i = size - 1; i >= 0; i--) {
output[count[(array[i] / place) % 10] - 1] = array[i];
count[(array[i] / place) % 10]--;
}

for (int i = 0; i < size; i++)


array[i] = output[i];
}

// Main function to implement radix sort


void radixsort(int array[], int size) {
// Get maximum element
int max = getMax(array, size);

// Apply counting sort to sort elements based on place value.


for (int place = 1; max / place > 0; place *= 10)
countingSort(array, size, place);
}
// Print an array
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}

// Driver code
int main() {
int array[] = {121, 432, 564, 23, 1, 45, 788};
int n = sizeof(array) / sizeof(array[0]);
radixsort(array, n);
printArray(array, n);
}
OUTPUT
COMPLEXITY
Let there be d digits in input integers. Radix Sort takes O(d*(n+b)) time
where b is the base for representing numbers, for example, for the decimal
system, b is 10. What is the value of d? If k is the maximum possible value,
then d would be O(logb(k)). So overall time complexity is O((n+b) * logb(k)).
Which looks more than the time complexity of comparison-based sorting
algorithms for a large k. Let us first limit k. Let k <= n c where c is a constant.
In that case, the complexity becomes O(nLogb(n)). But it still doesn’t beat
comparison-based sorting algorithms.
What if we make the value of b larger? What should be the value of b to
make the time complexity linear? If we set b as n, we get the time complexity
as O(n). In other words, we can sort an array of integers with a range from 1
to nc if the numbers are represented in base n (or every digit takes log2(n)
bits).
PROGRAM 15
 Program to sort an array of integers in ascending order using merge sort.
#include <stdio.h>

#include <stdlib.h>

// Merges two subarrays of arr[].

// First subarray is arr[l..m]

// Second subarray is arr[m+1..r]

void merge(int arr[], int l, int m, int

r)

int i, j, k;

int n1 = m - l + 1;

int n2 = r - m;

/* create temp arrays */

int L[n1], R[n2];

/* Copy data to temp arrays L[] and R[] */

for (i = 0; i < n1; i++)

L[i] = arr[l + i];

for (j = 0; j < n2; j++)

R[j] = arr[m + 1 + j];

/* Merge the temp arrays back into

arr[l..r]*/ i = 0; // Initial index of first

subarray

j = 0; // Initial index of second subarray

k = l; // Initial index of merged subarray

while (i < n1 && j < n2) {

if (L[i] <= R[j]) {

arr[k] = L[i];

i++;

else {

arr[k] = R[j];
j++;

} k+

+;

/* Copy the remaining elements of L[], if there

are any */

while (i < n1) {

arr[k] = L[i];

i++;

k++;

/* Copy the remaining elements of R[], if there

are any */

while (j < n2) {

arr[k] = R[j];

j++;

k++;

/* l is for left index and r is right index of the

sub-array of arr to be sorted */

void mergeSort(int arr[], int l, int r)

if (l < r) {

// Same as (l+r)/2, but avoids overflow for

// large l and h

int m = l + (r - l) / 2;

// Sort first and second halves

mergeSort(arr, l, m);

mergeSort(arr, m + 1, r);
merge(arr, l, m, r);

/* UTILITY FUNCTIONS */

/* Function to print an array */

void printArray(int A[], int size)

int i;

for (i = 0; i < size; i++)

printf("%d ", A[i]);

printf("\n");

/* Driver code */

int main()

int arr[] = { 12, 11, 13, 5, 6, 7 };

int arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Given array is \n");

printArray(arr, arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");

printArray(arr, arr_size);

return 0;

}
OUTPUT
COMPLEXITY
Time Complexity: O(N log(N)), Sorting arrays on different machines. Merge
Sort is a recursive algorithm and time complexity can be expressed as
following recurrence relation.
T(n) = 2T(n/2) + θ(n)
The above recurrence can be solved either using the Recurrence Tree
method or the Master method. It falls in case II of the Master Method and the
solution of the recurrence is θ(Nlog(N)). The time complexity of Merge Sort is
θ(Nlog(N) ) in all 3 cases (worst, average, and best) as merge sort always
divides the array into two halves and takes linear time to merge two halves.
PROGRAM 16
 Program to sort an array of integers in ascending order using quick sort.
// Quick sort in C

#include <stdio.h>

// function to swap elements

void swap(int *a, int *b) {

int t = *a;

*a = *b;

*b = t;

// function to find the partition position

int partition(int array[], int low, int high) {

// select the rightmost element as pivot

int pivot = array[high];

// pointer for greater element

int i = (low - 1);

// traverse each element of the array

// compare them with the pivot

for (int j = low; j < high; j++) {

if (array[j] <= pivot) {

// if element smaller than pivot is found

// swap it with the greater element pointed by i

i++;

// swap element at i with element at j

swap(&array[i], &array[j]);

}
}

// swap the pivot element with the greater element at i

swap(&array[i + 1], &array[high]);

// return the partition point

return (i + 1);

void quickSort(int array[], int low, int high) {

if (low < high) {

// find the pivot element such that

// elements smaller than pivot are on left of pivot

// elements greater than pivot are on right of pivot

int pi = partition(array, low, high);

// recursive call on the left of pivot

quickSort(array, low, pi - 1);

// recursive call on the right of pivot

quickSort(array, pi + 1, high);

// function to print array elements

void printArray(int array[], int size) {

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

printf("%d ", array[i]);

printf("\n");

// main function

int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};

int n = sizeof(data) / sizeof(data[0]);

printf("Unsorted Array\n");

printArray(data, n);

// perform quicksort on data

quickSort(data, 0, n - 1);

printf("Sorted array in ascending order: \n");

printArray(data, n);

}
OUTPUT
COMPLEXITY
Time taken by QuickSort, in general, can be written as follows.
T(n) = T(k) + T(n-k-1) + (n)
The first two terms are for two recursive calls, the last term is for the partition
process. k is the number of elements that are smaller than the pivot.
The time taken by QuickSort depends upon the input array and partition
strategy.
PROGRAM 17
 Program to sort an array of integers in ascending order using heap sort.
#include <stdio.h>

/* function to heapify a subtree. Here 'i' is the

index of root node in array a[], and 'n' is the size of heap. */

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

int largest = i; // Initialize largest as root

int left = 2 * i + 1; // left child

int right = 2 * i + 2; // right child

// If left child is larger than root

if (left < n && a[left] > a[largest])

largest = left;

// If right child is larger than root

if (right < n && a[right] > a[largest])

largest = right;

// If root is not largest

if (largest != i) {

// swap a[i] with a[largest]

int temp = a[i];

a[i] = a[largest];

a[largest] =

temp;

heapify(a, n, largest);

/*Function to implement the heap sort*/

void heapSort(int a[], int n)

for (int i = n / 2 - 1; i >= 0; i--)

heapify(a, n, i);

// One by one extract an element from heap

for (int i = n - 1; i >= 0; i--) {

/* Move current root element to end*/


// swap a[0] with a[i]

int temp = a[0];

a[0] = a[i];

a[i] =

temp;

heapify(a, i, 0);

/* function to print the array elements */

void printArr(int arr[], int n)

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

printf("%d", arr[i]);

printf(" ");

int main()

int a[] = {48, 10, 23, 43, 28, 26, 1};

int n = sizeof(a) / sizeof(a[0]);

printf("Before sorting array elements are - \n");

printArr(a, n);

heapSort(a, n);

printf("\nAfter sorting array elements are - \n");

printArr(a, n);

return 0;

}
OUTPUT
COMPLEXITY

Here the time complexity is O(N log N)


PROGRAM 18
 Program to sort an array of integers in ascending order using shell sort.
#include <stdio.h>

/* function to implement shellSort */

int shell(int a[], int n)

/* Rearrange the array elements at n/2, n/4, ..., 1 intervals */

for (int interval = n/2; interval > 0; interval /= 2)

for (int i = interval; i < n; i += 1)

/* store a[i] to the variable temp and make the ith position empty */

int temp = a[i];

int j;

for (j = i; j >= interval && a[j - interval] > temp; j -= interval)

a[j] = a[j - interval];

// put temp (the original a[i]) in its correct position

a[j] = temp;

return 0;

void printArr(int a[], int n) /* function to print the array elements */

int i;

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

printf("%d ", a[i]);

int main()
{

int a[] = { 33, 31, 40, 8, 12, 17, 25, 42 };

int n = sizeof(a) / sizeof(a[0]);

printf("Before sorting array elements are - \n");

printArr(a, n);

shell(a, n);

printf("\nAfter applying shell sort, the array elements are - \n");

printArr(a, n);

return 0;

}
OUTPUT
COMPLEXITY
Time complexity of the above implementation of Shell sort is O(n2). In the
above implementation, the gap is reduced by half in every iteration. There
are many other ways to reduce gaps which leads to better time complexity.
PROGRAM 19
 Program to demonstrate the use of linear search to search a given element in an array.

#include<stdio.h>
int main()
{
int a[20],i,x,n;
printf("How many elements?");
scanf("%d",&n);
printf("Enter array elements:\n");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
printf("\nEnter element to search:");
scanf("%d",&x);
for(i=0;i<n;++i)
if(a[i]==x)
break;
if(i<n)
printf("Element found at index %d",i);
else
printf("Element not found");
return 0;
}
OUTPUT
COMPLEXITY

Here the time complexity is O(N)


PROGRAM 20
 Program to demonstrate the use of binary search to search a given element in a sorted array
in ascending order.

#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n")
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);

return 0;
}
OUTPUT
COMPLEXITY

Here the time complexity is O(log n)

You might also like