0% found this document useful (0 votes)
1 views

Program

Uploaded by

userabhay1111111
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)
1 views

Program

Uploaded by

userabhay1111111
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/ 14

Practical No:- 1

Aim:- Write a program that implement Linear search algorithm.

LINEAR SEARCH

A linear search is the simplest method of searching a data set. Starting at the beginning
of the data set, each item of data is examined until a match is made. Once the item is found,
the search ends. If there is no match, the algorithm must deal with this.

LINEAR SEARCH ALGORITHM

Step 1: First, read the search element (Target element) in the array.
Step 2: In the second step compare the search element with the first element in the array.
Step 3: If both are matched, display “Target element is found” and terminate the Linear
Search function.
Step 4: If both are not matched, compare the search element with the next element in the
array.
Step 5: In this step, repeat steps 3 and 4 until the search (Target) element is compared with
the last element of the array.
Step 6 – If the last element in the list does not match, the Linear Search Function will be
terminated, and the message “Element is not found” will be displayed.

Example
Given an array arr[] of N elements, the task is to write a function to search a given
element x in arr[].
Examples:
Input: arr[] = {10, 20, 80, 30, 60, 50,110, 100, 130, 170}, x = 110;
Output: 6
Explanation: Element x is present at index 6
Input: arr[] = {10, 20, 80, 30, 60, 50,110, 100, 130, 170}, x = 175;
Output: -1
Explanation: Element x is not present in arr[].

PROGRAM:-

// C++ code to linearly search x in arr[]. If x

// is present then return its location, otherwise

// return -1

#include <iostream>
using namespace std;

int search(int arr[], int N, int x)

int i;

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

if (arr[i] == x)

return i;

return -1;

// Driver's code

int main(void)

int arr[] = { 2, 3, 4, 10, 40 };

int x = 10;

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

// Function call

int result = search(arr, N, x);

(result == -1)

? cout << "Element is not present in array"

: cout << "Element is present at index " << result;

return 0;

OUTPUT:-
Element is present at index 3
Practical No:- 2

Aim:- Write a program that implement Linear search algorithm.

Binary Search – Data Structure and Algorithm


Binary Search is defined as a searching algorithm used in a sorted array by repeatedly
dividing the search interval in half. The idea of binary search is to use the information that the
array is sorted and reduce the time complexity to O(log N).

Algorithm :

1. Divide the search space into two halves by finding the middle index “mid”.
2. Compare the middle element of the search space with the key.
3. If the key is found at middle element, the process is terminated.
Mid = Low + (high-low) /2
4. If the key is not found at middle element, choose which half will be used as the next
search space.
a. If the key is smaller than the middle element, then the left side is used for
next search.
b. If the key is larger than the middle element, then the right side is used for
next search.
5. This process is continued until the key is found or the total search space is
exhausted.

Program:
// C++ program to implement iterative Binary Search
#include <conio.h>
using namespace std;
// An iterative binary search function.
int binarySearch(int arr[], int l, int r, int x)
{
while (l <= r) {
int m = l + (r - l) / 2;

// Check if x is present at mid


if (arr[m] == x)
return m;

// If x greater, ignore left half


if (arr[m] < x)
l = m + 1;

// If x is smaller, ignore right half


else
r = m - 1;
}

// If we reach here, then element was not present


return -1;
}

// Driver code
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
(result == -1)
? cout << "Element is not present in array"
: cout << "Element is present at index " << result;
return 0;
}

Output:
Practical No. 3
Aim:- Write a program that implement stack (its operations) using i) Arrays ii) Linked list.

Algorithm:-

1. START
2. We begin with a class named Stack
3. Create a pointer top which we will use to carry out all operations
4. Initialize an array in which we'll be storing our data
5. Initialize a constructor as top = -1 indicating that stack is empty
6. Push() - function, we use this function to insert data into the stack, so first we
check if top==full i.e stack is full and data cannot be inserted. Else increment the
top pointer and insert the data.
7. Pop() - function, this function is used to remove data from the stack, first we check
if top==-1 i.e if stack is empty nothing is there to delete. Else delete the element in
top pointer and decrement it.
8. isEmpty() - function check whether stack is empty i.e to p== - 1 or top < 0
9. display() - function to display the contents of the stack, we iterate through the array
from the beginning till we reach the top pointer.
10. END

Program:-
#include <stdio.h>

#define SIZE 10

int S[SIZE+1];
int top = 0;

int is_empty() {
if(top == 0)
return 1;
return 0;
}

void push(int x) {
top = top+1;
if(top > SIZE) {
printf("Stack Overflow\n");
}
else {
S[top] = x;
}
}

int pop() {
if(is_empty()) {
printf("Stack Underflow\n");
return -1000;
}
else {
top = top-1;
return S[top+1];
}
}

int main() {
pop();
push(10);
push(20);
push(30);
push(40);
push(50);
push(60);
push(70);
push(80);
push(90);
push(100);
push(110);

int i;
for(i=1; i<=SIZE; i++) {
printf("%d\n",S[i]);
}
return 0;
}
Output:-
Stack Underflow
Stack Overflow
10
20
30
40
50
60
70
80
90
100
Practical No: 4

Aim: Write a program that implement Queue (its operations) using i) Arrays ii) Linked list.

A Queue is defined as a linear data structure


that is open at both ends and the operations are
performed in First In First Out (FIFO) order.

Queue – Linked List

Approach: To solve the problem follow the below idea:


we maintain two pointers, front, and rear. The front points to the first item of
the queue and rear points to the last item.
 enQueue(): This operation adds a new node after the rear and moves the
rear to the next node.
 deQueue(): This operation removes the front node and moves the front to
the next node.

Algorithm:
 Create a class QNode with data members integer data and QNode* next
 A parameterized constructor that takes an integer x value as a
parameter and sets data equal to x and next as NULL
 Create a class Queue with data members QNode front and rear
 Enqueue Operation with parameter x:
 Initialize QNode* temp with data = x
 If the rear is set to NULL then set the front and rear to temp and
return(Base Case)
 Else set rear next to temp and then move rear to temp
 Dequeue Operation:
 If the front is set to NULL return(Base Case)
 Initialize QNode temp with front and set front to its next
 If the front is equal to NULL then set the rear to NULL
 Delete temp from the memory

Program:

#include <bits/stdc++.h>
using namespace std;

struct QNode {
int data;
QNode* next;
QNode(int d)
{
data = d;
next = NULL;
}
};

struct Queue {
QNode *front, *rear;
Queue() { front = rear = NULL; }

void enQueue(int x)
{

// Create a new LL node


QNode* temp = new QNode(x);

// If queue is empty, then


// new node is front and rear both
if (rear == NULL) {
front = rear = temp;
return;
}

// Add the new node at


// the end of queue and change rear
rear->next = temp;
rear = temp;
}

// Function to remove
// a key from given queue q
void deQueue()
{
// If queue is empty, return NULL.
if (front == NULL)
return;

// Store previous front and


// move front one node ahead
QNode* temp = front;
front = front->next;

// If front becomes NULL, then


// change rear also as NULL
if (front == NULL)
rear = NULL;

delete (temp);
}
};

// Driver code
int main()
{

Queue q;
q.enQueue(10);
q.enQueue(20);
q.deQueue();
q.deQueue();
q.enQueue(30);
q.enQueue(40);
q.enQueue(50);
q.deQueue();
cout << "Queue Front : " << ((q.front != NULL) ? (q.front)->data : -1)<< endl;
cout << "Queue Rear : " << ((q.rear != NULL) ? (q.rear)->data : -1);
}

Output:

Queue Front : 40
Queue Rear : 50
Practical No: 5

Aim: Write a program that uses functions to perform the following operations on singly
linked list i) Creation ii) Insertion iii) Deletion iv) Traversal.

Theory:
A singly linked list is a linear data structure in which the elements are not stored in
contiguous memory locations and each element is connected only to its next element using a
pointer.

Each element of the Linked List is called a Node. A Linked List is formed by connecting
multiple nodes.
A node consists of two parts,
1. Data: It is the actual raw information that you want to maintain. It can be a video
object, a number, a character, etc.
2. Pointer to another node: It stores the link of the adjacent node.
Operations on singly linked list
1. Insertion
Insertion in a singly linked list can be performed in the following ways,
 Insertion at the start Insertion of a new node at the start of a singly linked list is
carried out in the following manner.
o Make the new node point to HEAD.
o Make the HEAD point to the new node.
Inserting a new node at the start is an O(1) operation.
2. Deletion
Deletion in a singly linked list can be performed in the following ways,
 Deletion at the start
The first node of the singly linked list can be deleted as follows,
o Make the HEAD point to its next element.
Deleting the first node of a singly linked list is an O(1) operation.

3. Display
To display the entire singly linked list, we need to traverse it from first to last.
In contrast to arrays, linked list nodes cannot be accessed randomly. Hence to reach the n-th
element, we are bound to traverse through all (n-1) elements.

Program:-
// Linked list operations in C++

#include <stdlib.h>

#include <iostream>
using namespace std;

// Create a node
struct Node {
int data;
struct Node* next;
};

void insertAtBeginning(struct Node** head_ref, int new_data) {


// Allocate memory to a node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

// insert the data


new_node->data = new_data;
new_node->next = (*head_ref);

// Move head to new node


(*head_ref) = new_node;
}

// Insert a node after a node


void insertAfter(struct Node* prev_node, int new_data) {
if (prev_node == NULL) {
cout << "the given previous node cannot be NULL";
return;
}

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));


new_node->data = new_data;
new_node->next = prev_node->next;
prev_node->next = new_node;
}

// Insert at the end


void insertAtEnd(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref; /* used in step 5*/

new_node->data = new_data;
new_node->next = NULL;

if (*head_ref == NULL) {
*head_ref = new_node;
return;
}

while (last->next != NULL) last = last->next;

last->next = new_node;
return;
}

// Delete a node
void deleteNode(struct Node** head_ref, int key) {
struct Node *temp = *head_ref, *prev;

if (temp != NULL && temp->data == key) {


*head_ref = temp->next;
free(temp);
return;
}
// Find the key to be deleted
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}

// If the key is not present


if (temp == NULL) return;

// Remove the node


prev->next = temp->next;

free(temp);
}

// Search a node
bool searchNode(struct Node** head_ref, int key) {
struct Node* current = *head_ref;

while (current != NULL) {


if (current->data == key) return true;
current = current->next;
}
return false;
}

// Sort the linked list


void sortLinkedList(struct Node** head_ref) {
struct Node *current = *head_ref, *index = NULL;
int temp;

if (head_ref == NULL) {
return;
} else {
while (current != NULL) {
// index points to the node next to current
index = current->next;

while (index != NULL) {


if (current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}

// Print the linked list


void printList(struct Node* node) {
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}

// Driver program
int main() {
struct Node* head = NULL;

insertAtEnd(&head, 1);
insertAtBeginning(&head, 2);
insertAtBeginning(&head, 3);
insertAtEnd(&head, 4);
insertAfter(head->next, 5);

cout << "Linked list: ";


printList(head);

cout << "\nAfter deleting an element: ";


deleteNode(&head, 3);
printList(head);

int item_to_find = 3;
if (searchNode(&head, item_to_find)) {
cout << endl << item_to_find << " is found";
} else {
cout << endl << item_to_find << " is not found";
}

sortLinkedList(&head);
cout << "\nSorted List: ";
printList(head);
}

Output:-

Linked list: 3 2 5 1 4
After deleting an element: 2 5 1 4
3 is not found
Sorted List: 1 2 4 5

You might also like