0% found this document useful (0 votes)
60 views68 pages

Data Structures Lab Report - CSE 2024

Uploaded by

YASH MODI
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)
60 views68 pages

Data Structures Lab Report - CSE 2024

Uploaded by

YASH MODI
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

Yash Modi

2022BCSE051

Department of Computer Science and Engineering


National Institute of Technology Srinagar
Hazratbal, Srinagar, Jammu and Kashmir - 190006, India.

LABORATORY REPORT
Data Structures Lab (CST251)

Submitted by

Yash Modi
2022BCSE051
II [Link]. CSE (4th Semester – Section ‘B’)

Submitted to

Dr. VENINGSTON K
Assistant Professor
Department of Computer Science and Engineering
National Institute of Technology Srinagar
Hazratbal, Srinagar, Jammu and Kashmir - 190006, India.

SPRING 2024
Yash Modi
2022BCSE051
<<Your Name>>
Yash Modi
2022BCSE051No.>>
<<Enrollment

CONTENTS

Page Faculty
Week # Date Experiment
No. Sign

Self-Declaration

I have done all the above programs on my own to the best of my knowledge.

Student’s Signature
Yash Modi
2022BCSE051
Yash Modi
2022BCSE051

WEEK 1

26-02-2024

Arrays and Structures

AIM: Concepts of Arrays and Structures

[Link] the 'nth' largest and smallest element in an array.

#include<bits/stdc++.h>

using namespace std;

void selection_sort(int ar[], int n){

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

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

if(ar[i]>ar[j]){

int temp=ar[i];

ar[i]=ar[j];

ar[j]=temp;}}}}

int nth_largest(int ar[],int n,int length){

return ar[length-n];}

int nth_smallest(int ar[],int n){

return ar[n-1];}

int main(){

int n,length;

cin>>length;

int ar[length];

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

cin>>ar[i];

cin>>n;

selection_sort(ar,length);

cout<<nth_largest(ar,n,length)<<endl;

cout<<nth_smallest(ar,n)<<endl;

return 0;

}
Yash Modi
2022BCSE051

2. Implement left shift with given number of steps.

#include<bits/stdc++.h>

using namespace std;

void left_shift(int ar[],int n,int step){

int ar_new[n]={0};

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

ar_new[(i-step)%n]=ar[i];

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

cout<<ar_new[i]<<" ";

int main() {

int ar[5]={1,2,3,4,5};

left_shift(ar,5,2);

return 0;

3. Implement cyclic right rotate with given number of steps.

#include<bits/stdc++.h>

using namespace std;

void left_shift(int ar[],int n,int step){

int ar_new[n]={0};

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

ar_new[(i+step)%n]=ar[i];

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

cout<<ar_new[i]<<" ";

}
Yash Modi
2022BCSE051

int main() {

int ar[5]={1,2,3,4,5};

left_shift(ar,5,2);

return 0;

4. Implement Intersection of two arrays.

#include<iostream>

using namespace std;

void intersection_of_array(int ar1[],int ar2[],int size){

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

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

if(ar1[i] == ar2[j]){

cout<<ar1[i]<<" ";

int main(){

int ar1[6]={1,2,5,6,8,7};

int ar2[6]={1,77,3,7,0,3};

intersection_of_array(ar1,ar2,6);

5. Reverse a given array.

#include<bits/stdc++.h>

using namespace std;

void reverse_array(int arr[],int size) {

int start = 0;

int end = size-1;

while(start<=end) {

swap(arr[start],arr[end]);

start++;

end--;
Yash Modi
2022BCSE051

int main() {

int size;

cin>>size;

int ar[size];

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

cin>>ar[i];

reverse_array(ar,size);

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

cout<<ar[i]<<" ";

return 0;

6. Design a program to manage employee records using structures in C++. The program should

provide the following functionalities:

Ensure that the program implements proper error handling and validation for user inputs. Use

appropriate data structures and algorithms to efficiently manage and manipulate employee

records.

#include<bits/stdc++.h>

using namespace std;

struct Student {

int roll_number;

string name;

int age;

float grade;

};

int main() {

int num_students;

float total_grade = 0.0;

float average_grade;
Yash Modi
2022BCSE051

cout << "Enter the number of students: ";

cin >> num_students;

Student students[num_students];

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

cout << endl << "Enter details for student " << i + 1 << ":" << endl;

cout << "Roll Number: ";

cin >> students[i].roll_number;

cout << "Name: ";

cin >> students[i].name;

cout << "Age: ";

cin >> students[i].age;

cout << "Grade: ";

cin >> students[i].grade;

total_grade += students[i].grade;

average_grade = total_grade / num_students;

cout << endl << "Average Grade of all students: " << average_grade << endl;

return 0;

} break;

case 2:

displayAll();

break;

case 3:

cout << "Enter date: ";

cin >> date;

displayJoined(date, true);

break;

case 4:
Yash Modi
2022BCSE051

cout << "Enter date: ";

cin >> date;

displayJoined(date, false);

break;

case 5:

cout << "Enter ID: ";

cin >> id;

searchByID(id);

break;

case 6:

cout << "Enter ID and new salary: ";

cin >> id >> newSal;

updateSal(id, newSal);

break;

case 7:

cout << "Enter ID: ";

cin >> id;

deleteByID(id);

break;

case 8:

calculateStats();

break;

case 9:

return 0;

default:

cout << "Invalid choice." << endl;

return 0;

}
Yash Modi
2022BCSE051

WEEK 2

04-03-2024

Searching Algorithm

AIM: Linear Search: Sequentially checks each element until target found.

Binary Search: Works on sorted lists, halves search interval.

Q1 Given an unsorted array of elements and a key value, write a function to determine if the key

exists in the array.

#include<bits/stdc++.h>

using namespace std;

int search_ar(int ar[],int n,int key){

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

if(ar[i]==key){

return i;

return -1;

int main(){

int n,key;

cin>>n;

int ar[n];

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

cin>>ar[i];

cin>>key;

cout<<search_ar(ar,n,key);

return 0;

Q2 Given a sorted array of elements and a key value, write a function to determine if the key

exists in the array.

#include<bits/stdc++.h>

using namespace std;


Yash Modi
2022BCSE051

int binary_search(int ar[],int start, int end , int key){

if(start>end)

return -1;

int mid=(start+end)/2;

if(key==ar[mid])

return mid;

else if(key<ar[mid])

binary_search(ar,start,mid-1,key);

else

binary_search(ar,mid+1,end,key);

int main() {

int ar[6]={2,1,10,9,2,0};

cout<<binary_search(ar,0,5,10);

cout<<binary_search(ar,0,5,1100);

Q3 Design a program to manage employee records using structures in C++.

#include <bits/stdc++.h>

using namespace std;

struct Emp {

int id;

string nm;

string dep;

string des;

string dob;

string doj;

double sal;

};

vector<Emp> emps;

void add() {

Emp e;

cin >> [Link] >> [Link] >> [Link] >> [Link] >> [Link] >> [Link] >> [Link];

emps.push_back(e);
Yash Modi
2022BCSE051

void displayAll() {

for (const auto& e : emps) {

cout << [Link] << " " << [Link] << " " << [Link] << " " << [Link] << " " << [Link] << " " << [Link] << " " << [Link] << endl;

void displayJoined(const string& date, bool before) {

for (const auto& e : emps) {

if ((before && [Link] < date) || (!before && [Link] > date)) {

cout << [Link] << " " << [Link] << " " << [Link] << " " << [Link] << " " << [Link] << " " << [Link] << " " << [Link] << endl;

void searchByID(int id) {

auto it = find_if([Link](), [Link](), [id](const Emp& e) { return [Link] == id; });

if (it != [Link]()) {

cout << it->id << " " << it->nm << " " << it->dep << " " << it->des << " " << it->dob << " " << it->doj << " " << it->sal <<
endl;

} else {

cout << "Employee not found." << endl;

void updateSal(int id, double newSal) {

auto it = find_if([Link](), [Link](), [id](const Emp& e) { return [Link] == id; });

if (it != [Link]()) {

it->sal = newSal;

} else {

cout << "Employee not found." << endl;

void deleteByID(int id) {

auto it = find_if([Link](), [Link](), [id](const Emp& e) { return [Link] == id; });

if (it != [Link]()) {

[Link](it);

} else {
Yash Modi
2022BCSE051

cout << "Employee not found." << endl;

void calculateStats() {

if ([Link]()) {

cout << "No employees in the records." << endl;

return;

double totalSal = 0;

double maxSal = emps[0].sal;

double minSal = emps[0].sal;

for (const auto& e : emps) {

totalSal += [Link];

maxSal = max(maxSal, [Link]);

minSal = min(minSal, [Link]);

cout << "Total employees: " << [Link]() << endl;

cout << "Avg salary: " << fixed << setprecision(2) << totalSal / [Link]() << endl;

cout << "Max salary: " << maxSal << endl;

cout << "Min salary: " << minSal << endl;

int main() {

int ch, id;

double newSal;

string date;

while (true) {

cout << "1. Add\n2. Display all\n3. Display joined before a date\n4. Display joined after a date\n5. Search by ID\n6.
Update salary\n7. Delete by ID\n8. Calculate stats\n9. Exit\n";

cin >> ch;

switch (ch) {

case 1:

add();

break;
Yash Modi
2022BCSE051

case 2:

displayAll();

break;

case 3:

cout << "Enter date: ";

cin >> date;

displayJoined(date, true);

break;

case 4:

cout << "Enter date: ";

cin >> date;

displayJoined(date, false);

break;

case 5:

cout << "Enter ID: ";

cin >> id;

searchByID(id);

break;

case 6:

cout << "Enter ID and new salary: ";

cin >> id >> newSal;

updateSal(id, newSal);

break;

case 7:

cout << "Enter ID: ";

cin >> id;

deleteByID(id);

break;

case 8:

calculateStats();

break;

case 9:

return 0;

default:

cout << "Invalid choice." << endl;


Yash Modi
2022BCSE051

return 0;

Q4 Design a structure called Car with attributes such as car_ID, make, model, year,

rental_price_per_day, from_date, and to_date. Write a program to allow users to input rental

car data, store them in an array of structures, and then calculate and display the total rental

cost for a particular car over a specified number of days.

#include<bits/stdc++.h>

using namespace std;

struct Car{

string car_ID,make,model,year;

int rental_price_per_day, from_date,to_date;

};

int main() {

int n;

cin>>n;

Car cars[n];

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

cout<<"Car ID";

cin>>cars[i].car_ID;

cout<<"Car Make";

cin>>cars[i].make;

cout<<"Car Model";

cin>>cars[i].model;

cout<<"Car Year";

cin>>cars[i].year;
Yash Modi
2022BCSE051

cout<<"Car rent_per_day";

cin>>cars[i].rental_price_per_day;

cout<<"Car from_date";

cin>>cars[i].from_date;

cout<<"Car to_date";

cin>>cars[i].to_date;

string carID;

cout<<"Enter the Car details";

cin>>carID;

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

if(carID==cars[i].car_ID)

cout<<"Total Number of day used:"<<-(cars[i].from_date-cars[i].to_date)<<endl<<"Total rent of the car:"<<-


(cars[i].from_date-cars[i].to_date)*cars[i].rental_price_per_day;

return 0;

Q5 Given a 2D array of integers where each row and column are sorted in ascending order, write

a function to efficiently search for a target value in the array. Print the # of comparisons

required before finding a target value through row-based and column-based searches.

#include<bits/stdc++.h>

using namespace std;

void binary_search_2d(vector<vector<int>> &ar, int key){

int row=[Link]();

int col=ar[0].size();

int start=0;

int end=row*col-1;

int comparisons=0;
Yash Modi
2022BCSE051

while(start<=end){

int mid=(start+end)/2;

comparisons++;

if(ar[mid/col][mid%col]==key){

cout<<"Total Comparisons are:"<<comparisons<<endl;

cout<<"row: "<<mid/col<<" col: "<<mid%col;

return;

else if(ar[mid/col][mid%col]<key)

start=mid+1;

else

end=mid-1;

int main() {

vector<vector<int>> ar={{1,2,3},{4,5,6},{7,8,9}};

binary_search_2d(ar,8);

return 0;

Q6 Given a sorted array of integers and a target value, write efficient functions to find the first

and last occurrences of the key value in the array.

#include<bits/stdc++.h>

using namespace std;

int first_occu(int ar[], int n, int key){

int left=0,right=n-1;

int first_pos=-1,mid=0;

while(left<=right){

mid=(left+right)/2;

if(ar[mid]==key){

first_pos=mid;

right=mid-1;

else if(ar[mid]<key){
Yash Modi
2022BCSE051

left=mid+1;

else{

right=mid-1;

return first_pos;

int last_occu(int ar[], int n, int key){

int left=0,right=n-1;

int last_pos=-1,mid=0;

while(left<=right){

mid=(left+right)/2;

if(ar[mid]==key){

last_pos=mid;

left=mid+1;

else if(ar[mid]<key){

left=mid+1;

else{

right=mid-1;

return last_pos;

int main() {

int ar[8]={3,4,4,4,5,5,8,9};

cout<<first_occu(ar,8,4);

cout<<last_occu(ar,8,4);

return 0;

}
Yash Modi
2022BCSE051

Q7 Given a rotated/wrapped sorted array of integers and a key value, write an efficient function

to determine if the key value exists.

#include<bits/stdc++.h>

using namespace std;

int binary_search(int ar[],int start, int end , int key){

if(start>end)

return -1;

int mid=(start+end)/2;

if(key==ar[mid])

return mid;

else if(key<ar[mid])

binary_search(ar,start,mid-1,key);

else

binary_search(ar,mid+1,end,key);

int search_shifted(int ar[],int n,int key){

int shift=1,i=0;

while(ar[i]<ar[i+1]){

shift++;

i++;

if(key<=ar[shift-1])

return binary_search(ar,0,shift-1,key);

else

return binary_search(ar,shift-1,n-1,key);

int main() {

int ar[8]={39,42,95,11,15,21,30,33};

cout<<search_shifted(ar,8,95);

return 0;

Q8 Write a function to find all peak elements from an array of integers. A peak element is an

element that is greater than or equal to its neighbours. Consider that the input array is

wrapped around.
Yash Modi
2022BCSE051

#include<bits/stdc++.h>

using namespace std;

void check_peak(int ar[],int n){

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

if(i==0 && ar[i]>=ar[i+1])

cout<<ar[i]<<" ";

else if(ar[i]>=ar[i+1] && ar[i]>=ar[i-1]){

cout<<ar[i]<<" ";

int main() {

int ar[7]={100, 20, 15, -2, 23, 90, 67};

check_peak(ar,7);

return 0;

}
Yash Modi
2022BCSE051
Yash Modi
2022BCSE051

WEEK 3

11-03-2024

Sorting Algorithm

AIM: Implement the mentioned sorting algorithms [iterative algorithms]

Q1 Implement the generic bubble sort algorithm to sort an array of elements in ascending order.

Modify the bubble sort implementation to count the number of swaps made during the

sorting process. Print the total number of swaps after sorting the array.

#include<bits/stdc++.h>

using namespace std;

void bubble_sort(int ar[],int n){

int count_swap=0;

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

int flag=0;

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

if(ar[j]>ar[j+1]){

swap(ar[j],ar[j+1]);

flag=1;

count_swap++;

if(flag==0){

break;

int main() {

int ar[10]={6,1,9,0,2,5,1,2,50,65};

bubble_sort(ar,10);

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

cout<<ar[i]<<" ";

return 0;

}
Yash Modi
2022BCSE051

Q2 Implement the insertion sort algorithm to sort an array of integers in ascending order. Modify

the insertion sort implementation to sort an array of students’ structures

#include<bits/stdc++.h>

using namespace std;

void insertion_sort(string ar[],int n){

int i=0;

string key;

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

key=ar[j];

i=j-1;

while(i>=0 && ar[i]>key){

ar[i+1]=ar[i];

i--;

ar[i+1]=key;

int main() {

string names[6] = {"yash", "aditya", "apratim", "sumit", "mayank", "jatin"};

insertion_sort(names,6);

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

cout<<names[i]<<" ";

return 0;

Q3 Modify the insertion sort implementation to employ binary search to find the correct position

of the element to be placed in the sorted subarray to decrease the # of comparisons required.

Run the native and modified insertion sort on the same inputs and assess the performance of

the modified algorithm under different data distributions.

#include <iostream>

using namespace std;

int binarySearch(int arr[], int key, int left, int right) {

while (left <= right) {

int mid= left + (right - left) / 2;

if (arr[mid] == key)
Yash Modi
2022BCSE051

return mid;

else if (arr[mid] < key)

left = mid +1;

else

right = mid -1;

return left;

void insertion_sort2(int arr[], int n) {

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

int key = arr[i];

int j = i -1;

int pos = binarySearch(arr, key, 0, j);

while (j >= pos) {

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

j--;

arr[j +1] = key;

int main() {

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

insertion_sort2(arr,5);

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

cout << arr[i] << " ";

return 0;

Q4 Implement the selection sort algorithm to sort an array of integers in ascending order. Modify

the selection sort implementation to find the kth smallest element in an array.

#include<bits/stdc++.h>

using namespace std;

int selection_sort_kth(int ar[], int n, int k){

for(int i=0;i<n;i++){
Yash Modi
2022BCSE051

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

if(ar[i]>ar[j]){

int temp=ar[i];

ar[i]=ar[j];

ar[j]=temp;

return ar[k-1];

int main(){

int ar[6]={2,6,1,88,2,0};

cout<<selection_sort_kth(ar,6,2);

Q5 Compare the performance of bubble, insertion, and selection sort algorithms based on their

sorting time and sensitivity to the randomly generated input data distribution. Identify the

strengths and weaknesses of each algorithm under different scenarios(i.e., random collection,

sorted and reversely sorted).

#include<bits/stdc++.h>

using namespace std;

using namespace std::chrono;

vector<int> randomVector(int n, int upperBound) {

vector<int> vec(n);

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

vec[i] = rand() % upperBound;

return vec;

void printVector(const vector<int>& vec) {

for (int i = 0; i < [Link](); i++) {

cout << vec[i] << " ";

}
Yash Modi
2022BCSE051

cout << endl;

int bubbleSort(vector<int>& arr) {

int n = [Link]();

int swap = 0;

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

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

if (arr[j] > arr[j+1]) {

swap++;

int temp = arr[j];

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

arr[j+1] = temp;

return swap;

int insertionSort(vector<int>& arr) {

int n = [Link]();

int swap = 0;

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

int key = arr[i];

int j = i - 1;

while (j >= 0 && arr[j] > key) {

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

j = j - 1;

swap++;

arr[j + 1] = key;

return swap;

}
Yash Modi
2022BCSE051

int selectionSort(vector<int>& arr) {

int n = [Link]();

int swap = 0;

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

int min_idx = i;

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

if (arr[j] < arr[min_idx]) {

min_idx = j;

swap++;

int temp = arr[min_idx];

arr[min_idx] = arr[i];

arr[i] = temp;

return swap;

int main() {

int numValues = 1000;

int upperBound = 1000;

vector<int> values = randomVector(numValues, upperBound);

cout << "Before sorting:" << endl;

printVector(values);

// Bubble Sort

vector<int> bubbleValues = values;

auto bubble_start = high_resolution_clock::now();

int bubble_swaps = bubbleSort(bubbleValues);

auto bubble_stop = high_resolution_clock::now();

auto bubble_duration = duration_cast<microseconds>(bubble_stop - bubble_start);

// Insertion Sort

vector<int> insertionValues = values;


Yash Modi
2022BCSE051

auto insertion_start = high_resolution_clock::now();

int insertion_swaps = insertionSort(insertionValues);

auto insertion_stop = high_resolution_clock::now();

auto insertion_duration = duration_cast<microseconds>(insertion_stop - insertion_start);

// Selection Sort

vector<int> selectionValues = values;

auto selection_start = high_resolution_clock::now();

int selection_swaps = selectionSort(selectionValues);

auto selection_stop = high_resolution_clock::now();

auto selection_duration = duration_cast<microseconds>(selection_stop - selection_start);

cout << "After sorting:" << endl;

cout << "Bubble Sort - Time taken: " << bubble_duration.count() << " microseconds, Swaps: " << bubble_swaps << endl;

cout << "Insertion Sort - Time taken: " << insertion_duration.count() << " microseconds, Swaps: " << insertion_swaps <<
endl;

cout << "Selection Sort - Time taken: " << selection_duration.count() << " microseconds, Swaps: " << selection_swaps <<
endl;

return 0;

Q6 Implement a strategy to terminate the selection sorting process early if the array becomes

sorted before completing all iterations. Track whether swaps were made in each iteration and

stop sorting if no swaps occur.

#include <iostream>

using namespace std;

void bubbleSort(int arr[], int n) {

bool swapped;

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

swapped = false;

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

if (arr[j] > arr[j + 1]) {

swap(arr[j], arr[j + 1]);


Yash Modi
2022BCSE051

swapped = true;

if (!swapped) {

cout << "Array is already sorted"<<endl;

return;

int main() {

int arr[5] = {64, 25, 12, 22, 11};

bubbleSort(arr,5);

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

cout << arr[i] << " ";

return 0;

Q7 Implement the counting sort algorithm to sort an array of positive integers in ascending order.

Also, the counting sort implementation should be modified to sort an array of characters in

lexicographical order. Test the implementation with various strings and verify its correctness.

#include<bits/stdc++.h>

using namespace std;

void countingSort(int arr[], int n, int max_value) {

vector<int> count(max_value + 1, 0), output(n);

for (int i = 0; i < n; ++i) ++count[arr[i]];

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

for (int i = n - 1; i >= 0; --i) output[count[arr[i]] - 1] = arr[i], --count[arr[i]];

for (int i = 0; i < n; ++i) arr[i] = output[i];

int main() {

int arr[7]={4,2,2,8,3,3,1};

countingSort(arr,7,8);

for(int i=0;i<7;i++){
Yash Modi
2022BCSE051

cout<<arr[i]<<" ";

return 0;

Q8 Implement the radix sort algorithm to sort an array of positive integers in ascending order.

Modify the radix sort implementation to sort an array of strings in lexicographical order.

#include <iostream>

#include <algorithm>

using namespace std;

void radixSort(int arr[], int n) {

int max_value = *max_element(arr, arr + n);

for (int exp = 1; max_value / exp > 0; exp *= 10) {

int output[n], count[10] = {0};

for (int i = 0; i < n; ++i) ++count[(arr[i] / exp) % 10];

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

for (int i = n - 1; i >= 0; --i) output[--count[(arr[i] / exp) % 10]] = arr[i];

for (int i = 0; i < n; ++i) arr[i] = output[i];

void radixSort(string arr[], int n) {

int max_length = 0;

for (int i = 0; i < n; ++i) max_length = max(max_length, (int)arr[i].length());

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

string output[n];

int count[256] = {0};

for (int j = 0; j < n; ++j) ++count[i < arr[j].length() ? arr[j][i] : 0];

for (int j = 1; j < 256; ++j) count[j] += count[j - 1];

for (int j = n - 1; j >= 0; --j) output[--count[i < arr[j].length() ? arr[j][i] : 0]] = arr[j];

for (int j = 0; j < n; ++j) arr[j] = output[j];

int main() {

int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};


Yash Modi
2022BCSE051

radixSort(arr,8);

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

cout<<arr[i]<<" ";

cout<<endl;

string str_arr[] = {"ok", "efgh", "abcd", "namaste", "hello"};

radixSort(str_arr,5);

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

cout<<str_arr[i]<<" ";

return 0;

Q9 Implement the Radix Sort algorithm that handles input arrays with a mix of positive and

negative integers.

#include <iostream>

#include <vector>

#include <algorithm>

#include <cmath>

using namespace std;

void countSort(vector<int>& arr, int exp) {

const int radix = 10;

vector<int> output([Link]()), count(radix * 2, 0);

for (int num : arr) {

int index = (num / exp) % radix;

count[index + radix]++;

for (int i = 1; i < radix * 2; ++i) {

count[i] += count[i - 1];

for (int i = [Link]() - 1; i >= 0; --i) {


Yash Modi
2022BCSE051

int index = (arr[i] / exp) % radix;

output[count[index + radix] - 1] = arr[i];

count[index + radix]--;

arr = output;

void radixSort(vector<int>& arr) {

int max_val = *max_element([Link](), [Link]());

int min_val = *min_element([Link](), [Link]());

int max_abs = max(abs(max_val), abs(min_val));

for (int exp = 1; max_abs / exp > 0; exp *= 10) {

countSort(arr, exp);

if (min_val < 0) {

int idx = 0;

for (int i = [Link]() - 1; i >= 0; --i) {

if (arr[i] < 0) {

swap(arr[i], arr[idx]);

idx++;

} else {

break;

int main() {

vector<int> arr = {170, -45, 75, -90, 802, -24, 2, 66};

radixSort(arr);

cout << "Sorted array: ";

for (int num : arr) {

cout << num << " ";

}
Yash Modi
2022BCSE051

cout << endl;

return 0;

}
Yash Modi
2022BCSE051

WEEK 4

18-03-2024

Sorting Algorithms II

AIM: Implement the mentioned sorting algorithms [Recursive Technique]

1]Quick Sort

2]Merge Sort

Q1 Implement the Merge Sort algorithm as a function that takes an array of integers and sorts it.

#include<bits/stdc++.h>

using namespace std;

void merge(int ar[], int l, int mid, int r) {

int n1 = mid - l + 1, n2 = r - mid;

int a[n1], b[n2];

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

a[i] = ar[l + i];

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

b[i] = ar[mid + 1 + i];

int i = 0, j = 0, k = l;

while(i < n1 && j < n2)

if(a[i] > b[j]) ar[k++] = b[j++];

else ar[k++] = a[i++];

while(i < n1) ar[k++] = a[i++];

while(j < n2) ar[k++] = b[j++];

void merge_sort(int ar[], int l, int r) {

if(l < r) {

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

merge_sort(ar, l, mid);

merge_sort(ar, mid + 1, r);

merge(ar, l, mid, r);

int main() {

int ar[6] = {3, 1, 4, 72, 10, 0};

merge_sort(ar, 0, 5);
Yash Modi
2022BCSE051

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

cout << ar[i] << " ";

return 0;

Q2 Modify the Merge Sort implementation to sort an array of strings in lexicographical order.

Write a function that takes an array of strings as input and sorts it using Merge Sort.

#include<bits/stdc++.h>

using namespace std;

void merge(string ar[], int l, int mid, int r) {

int n1 = mid - l + 1, n2 = r - mid;

string a[n1], b[n2];

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

a[i] = ar[l + i];

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

b[i] = ar[mid + 1 + i];

int i = 0, j = 0, k = l;

while(i < n1 && j < n2)

if(a[i] > b[j]) ar[k++] = b[j++];

else ar[k++] = a[i++];

while(i < n1) ar[k++] = a[i++];

while(j < n2) ar[k++] = b[j++];

void merge_sort(string ar[], int l, int r) {

if(l < r) {

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

merge_sort(ar, l, mid);

merge_sort(ar, mid + 1, r);

merge(ar, l, mid, r);

int main() {

string ar[6] = {"yash", "modi", "2022", "bcse", "051"};

merge_sort(ar, 0, 5);

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


Yash Modi
2022BCSE051

cout << ar[i] << " ";

return 0;

Q3 Implement the Quick Sort algorithm as a function that takes an array of integers and sorts it.

#include<bits/stdc++.h>

using namespace std;

int partition(int ar[], int l, int r) {

int pivot = ar[r];

int i = l - 1;

for(int j = l; j < r; j++) {

if(ar[j] < pivot) {

i++;

swap(ar[i], ar[j]);

swap(ar[r], ar[i + 1]);

return i + 1;

void quick_sort(int ar[], int l, int r) {

if(l < r) {

int pivot = partition(ar, l, r);

quick_sort(ar, l, pivot - 1);

quick_sort(ar, pivot + 1, r);

int main() {

int ar[6] = {3, 1, 4, 72, 10, 0};

quick_sort(ar, 0, 5);

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

cout << ar[i] << " ";

return 0;

Q4 Modify the Quick Sort implementation to randomly select the pivot element instead of always
Yash Modi
2022BCSE051

choosing the last element as the pivot. Implement a function that chooses a random pivot for

each partitioning step. Evaluate the performance of the randomized Quick Sort algorithm and

compare it with the standard Quick Sort.

#include <bits/stdc++.h>

#include <chrono>

using namespace std;

using namespace std::chrono;

int partition(int ar[], int l, int r) {

int pivot = ar[r];

int i = l - 1;

for(int j = l; j < r; j++) {

if(ar[j] < pivot) {

i++;

swap(ar[i], ar[j]);

swap(ar[r], ar[i + 1]);

return i + 1;

int random_partition(int ar[], int l, int r) {

int random_index = l + rand() % (r - l + 1);

swap(ar[random_index], ar[r]);

return partition(ar, l, r);

void quick_sort_randomized(int ar[], int l, int r) {

if (l < r) {

int pivot = random_partition(ar, l, r);

quick_sort_randomized(ar, l, pivot - 1);

quick_sort_randomized(ar, pivot + 1, r);

}
Yash Modi
2022BCSE051

int main() {

srand(time(0));

int n = 100000;

int ar[n];

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

ar[i] = rand() % 1000000;

auto start_randomized = high_resolution_clock::now();

quick_sort_randomized(ar, 0, n - 1);

auto stop_randomized = high_resolution_clock::now();

auto duration_randomized = duration_cast<microseconds>(stop_randomized - start_randomized);

cout << "Randomized Quick Sort execution time: " << duration_randomized.count() << " microseconds" << endl;

return 0;

Q5 Modify the Quick Sort implementation to handle arrays with duplicate elements efficiently

using three-way partitioning.

#include<iostream>

using namespace std;

void partition(int arr[], int s, int e, int &le, int &ge) {

int p = arr[s], l = s, g = e, i = s;

while (i <= g) {

if (arr[i] < p) swap(arr[i++], arr[l++]);

else if (arr[i] > p) swap(arr[i], arr[g--]);

else i++;

le = l - 1;

ge = g + 1;
Yash Modi
2022BCSE051

void QuickSort(int arr[], int s, int e) {

if (s >= e) return;

int le, ge;

partition(arr, s, e, le, ge);

QuickSort(arr, s, le);

QuickSort(arr, ge, e);

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

for (int i = 0; i < size; i++) cout << arr[i] << " ";

cout << endl;

int main() {

int arr[] = {38, 27, 27, 43, 3, 9, 3, 82, 10};

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

cout << "Unsorted Array : ";

printArray(arr, size);

QuickSort(arr, 0, size - 1);

cout << "Sorted Array : ";

printArray(arr, size);

return 0;

Q6 Use Quick sort to develop an algorithm to find median of an array of integers. The median of

a set of numbers is the middle value when the numbers are arranged in ascending or

descending order.

#include<iostream>

using namespace std;

int Partition(int arr[], int l, int r) {

int lst = arr[r], i = l;

for (int j = l; j < r; j++) {


Yash Modi
2022BCSE051

if (arr[j] < lst) swap(arr[i++], arr[j]);

swap(arr[i], arr[r]);

return i;

int randomPartition(int arr[], int l, int r) {

int pivot = l + rand() % (r - l + 1);

swap(arr[pivot], arr[r]);

return Partition(arr, l, r);

void MedianUtil(int arr[], int l, int r, int k, int& a, int& b) {

if (l <= r) {

int partitionIndex = randomPartition(arr, l, r);

if (partitionIndex == k) {

b = arr[partitionIndex];

if (a != -1) return;

} else if (partitionIndex == k - 1) {

a = arr[partitionIndex];

if (b != -1) return;

if (partitionIndex >= k) MedianUtil(arr, l, partitionIndex - 1, k, a, b);

else MedianUtil(arr, partitionIndex + 1, r, k, a, b);

void findMedian(int arr[], int n) {

int a = -1, b = -1;

if (n % 2 == 1) MedianUtil(arr, 0, n - 1, n / 2, a, b);

else MedianUtil(arr, 0, n - 1, n / 2, a, b);

int ans = (n % 2 == 1) ? b : (a + b) / 2;

cout << "Median = " << ans;

int main() {

int arr[] = { 12, 3, 5, 7, 4, 19, 26 };

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

findMedian(arr, n);
Yash Modi
2022BCSE051

return 0;

Q8Write a function to find the median of an array of integers using the Median of

Medians algorithm. Employ this median of medians finding algorithm to revise the quick sort

#include<iostream>

#include <chrono>

using namespace std;

using namespace std::chrono;

int partitionFirstPivot(int arr[], int s, int e) {

int pivot = arr[s];

int count = 0;

for(int i = s + 1; i <= e; i++) {

if(arr[i] <= pivot) {

count++;

int pivotIndex = s + count;

swap(arr[pivotIndex], arr[s]);

int i = s, j = e;

while (i < pivotIndex && j > pivotIndex) {

while (arr[i] < pivot) {

i++;

while (arr[j] > pivot) {

j--;

if(i < pivotIndex && j > pivotIndex) {

swap(arr[i++], arr[j--]);

return pivotIndex;

}
Yash Modi
2022BCSE051

void QuickSortFirstPivot(int arr[], int s, int e) {

if(s >= e) {

return;

int p = partitionFirstPivot(arr, s, e);

QuickSortFirstPivot(arr, s, p - 1);

QuickSortFirstPivot(arr, p + 1, e);

int partitionLastPivot(int arr[], int s, int e) {

int pivot = arr[e];

int pivotIndex = s;

for(int i = s; i < e; i++) {

if(arr[i] <= pivot) {

swap(arr[i], arr[pivotIndex]);

pivotIndex++;

swap(arr[pivotIndex], arr[e]);

return pivotIndex;

void QuickSortLastPivot(int arr[], int s, int e) {

if(s >= e) {

return;

int p = partitionLastPivot(arr, s, e);

QuickSortLastPivot(arr, s, p - 1);

QuickSortLastPivot(arr, p + 1, e);

}
Yash Modi
2022BCSE051

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

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

cout << arr[i] << " ";

cout << endl;

int* randomArray(int n, int upperBound) {

int* arr = new int[n];

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

arr[i] = rand() % upperBound;

return arr;

int main() {

int numValues = 1000;

int upperBound = 25;

int* values = randomArray(numValues, upperBound);

auto QuickSortFirstPivotStart = high_resolution_clock::now();

QuickSortFirstPivot(values, 0, numValues);

auto QuickSortFirstPivotStop = high_resolution_clock::now();

auto QuickSortFirstPivotDuration = duration_cast<microseconds>(QuickSortFirstPivotStop - QuickSortFirstPivotStart);

cout << "Time for choosing first element as pivot: " << [Link]() << " microseconds" << endl;

auto QuickSortLastPivotStart = high_resolution_clock::now();

QuickSortLastPivot(values, 0, numValues);

auto QuickSortLastPivotStop = high_resolution_clock::now();

auto QuickSortLastPivotDuration = duration_cast<microseconds>(QuickSortLastPivotStop - QuickSortLastPivotStart);

cout << "Time for choosing last element as pivot: " << [Link]() << " microseconds" << endl;

delete[] values;
Yash Modi
2022BCSE051

WEEK 5

01-04-2024

Single Linked List

Aim: Implement the following operations on Single Linked List.

Q1 Write a program to create a single linked list. Include methods to insert elements at the

beginning, end, a specific position of the list, and a specific element of the list, delete

elements, search for a value, and display the contents of the list.

#include<bits/stdc++.h>

using namespace std;

class node{

public:

int data;

node* next;

node(int data){

this->data=data;

next=NULL;

};

void insert_at_start(int data,node* &head){

node* temp= new node(data);

if(head==NULL)

head=temp;

else{

temp->next=head;

head=temp;

void insert_at_tail(int data,node* &head){

node* temp=head;

while(temp->next!=NULL){

temp=temp->next;

node* n= new node(data);

temp->next=n;
Yash Modi
2022BCSE051

void insert_at_position(int data, node* &head,int pos){

int position=1;

node* temp=head;

while((position!=pos-1) && temp->next!=NULL){

temp=temp->next;

position++;

node* temp2=temp->next;

node* n= new node(data);

temp->next=n;

n->next=temp2;

void search_by_value(node* head,int value){

int position=1;

bool flag=true;

while(head->next!=NULL){

position++;

if(head->data==value){

cout<<"element found at : "<<position<<endl;

flag=false;

break;

head=head->next;

if(flag)

cout<<" Element not found sorry"<<endl;

int search_by_position(node* head, int pos){

node* temp=head;

int count=0;

while(count!=pos){

temp=temp->next;

count++;
Yash Modi
2022BCSE051

return temp->data;

void show_list(node* head){

while(head->next!=NULL){

cout<<head->data<<" ";

head=head->next;

cout<<endl;

void delete_at_value(node* head,int value){

// int position=1;

while(head->data!=value){

head=head->next;

node* temp=head->next;

head->next=head->next->next;

// delete temp;

free(temp);

void delete_at_position(node* head,int pos){

int position=1;

while(position=pos-1){

head=head->next;

node* temp=head->next;

head->next=head->next->next;

// delete temp;

free(temp);

int main() {

node* head=new node(1);

insert_at_tail(2,head);

insert_at_tail(3,head);
Yash Modi
2022BCSE051

insert_at_tail(4,head);

insert_at_tail(5,head);

insert_at_tail(6,head);

search_by_value(head,5);

insert_at_position(10,head,3);

show_list(head);

delete_at_position(head,5);

show_list(head);

cout<<search_by_position(head,3);

return 0;

Q2 Write a function to reverse a single linked list in-place. Implement an iterative solution to

reverse the list.

#include<bits/stdc++.h>

using namespace std;

class node{

public:

int data;

node* next;

node(int data){

this->data=data;

next=NULL;

};

void insert_at_tail(int data,node* &head){

node* temp=head;

while(temp->next!=NULL){

temp=temp->next;

node* n= new node(data);

temp->next=n;

void show_list(node* head){


Yash Modi
2022BCSE051

while(head!=NULL){

cout<<head->data<<" ";

head=head->next;

cout<<endl;

void list_reversal(node* &head){

node* prev=NULL;

node* curr=head;

node* next=head->next;

while(curr!=NULL){

next = curr->next;

curr->next=prev;

prev=curr;

curr=next;

head=prev;

int main() {

node* head=new node(1);

insert_at_tail(2,head);

insert_at_tail(3,head);

insert_at_tail(4,head);

insert_at_tail(5,head);

insert_at_tail(6,head);

list_reversal(head);

show_list(head);

return 0;

Q3 Write a function that takes two sorted single linked lists as input and merges them into a single

sorted list. The original lists should remain unchanged.

#include<bits/stdc++.h>

using namespace std;


Yash Modi
2022BCSE051

class node{

public:

int data;

node* next;

node(int data){

this->data = data;

next = NULL;

};

void insert_at_tail(int data, node* &head){

node* temp = head;

while(temp->next != NULL){

temp = temp->next;

node* n = new node(data);

temp->next = n;}

void show_list(node* head){

while(head != NULL){

cout << head->data << " ";

head = head->next;

cout << endl;

void merge_list(node* head1, node* head2, node* &dummy, int size1, int size2){

int i = 0, j = 0;

node* temp1 = head1;

node* temp2 = head2;

node* temp3 = dummy;

while(i < size1 && j < size2){

if(temp1->data > temp2->data){

temp3->next = temp2;

temp2 = temp2->next;

i++;

else{
Yash Modi
2022BCSE051

temp3->next = temp1;

temp1 = temp1->next;

j++;

temp3 = temp3->next;

while(i < size1){

temp3->next = temp1;

temp1 = temp1->next;

temp3 = temp3->next;

i++;

while(j < size2){

temp3->next = temp2;

temp2 = temp2->next;

temp3 = temp3->next;

j++;

int main() {

node* head = new node(11);

insert_at_tail(20, head);

insert_at_tail(31, head);

insert_at_tail(49, head);

insert_at_tail(50, head);

insert_at_tail(69, head);

node* head2 = new node(2);

insert_at_tail(1, head2);

insert_at_tail(44, head2);

insert_at_tail(45, head2);

insert_at_tail(60, head2);

insert_at_tail(90, head2);

insert_at_tail(100, head2);

node* dummy = new node(0);


Yash Modi
2022BCSE051

merge_list(head, head2, dummy, 5, 6);

show_list(dummy->next);

return 0;

Q4 Write a function to remove the nth node from the end of a single linked list and return the head of the modified list.

#include<bits/stdc++.h>

using namespace std;

class node{

public:

int data;

node* next;

node(int data){

this->data = data;

next = NULL;

};

void insert_at_tail(int data, node* &head){

node* temp = head;

while(temp->next != NULL){

temp = temp->next;

node* n = new node(data);

temp->next = n;

void show_list(node* head){

while(head != NULL){

cout << head->data << " ";

head = head->next;

cout << endl;

}
Yash Modi
2022BCSE051

void delete_at_position(node* head, int nth, int size) {

int position = 1;

while (position != size-nth) {

head = head->next;

position++;

node* temp = head->next;

head->next = head->next->next;

delete temp;

int main() {

node* head = new node(11);

insert_at_tail(20, head);

insert_at_tail(31, head);

insert_at_tail(49, head);

insert_at_tail(50, head);

insert_at_tail(69, head);

delete_at_position(head,2,6);

show_list(head);

return 0;

Q5 Write a function to find the intersection of two singly linked lists. If the lists do not

intersect, return null.

#include<bits/stdc++.h>

using namespace std;

class node{

public:

int data;

node* next;

node(int data){

this->data = data;

next = NULL;

}
Yash Modi
2022BCSE051

};

void insert_at_tail(int data, node* &head){

node* temp = head;

while(temp->next != NULL){

temp = temp->next;

node* n = new node(data);

temp->next = n;

void show_list(node* head){

while(head != NULL){

cout << head->data << " ";

head = head->next;

cout << endl;

void find_mid(node* head){

node* temp=head;

int size=0,count=0;

int mid;

while(temp->next!=NULL){

temp=temp->next;

size++;

if(size%2==0){

mid=size/2;

if(size%2!=0){

mid=size/2;

mid++;

while(count!=mid){

temp=temp->next;

count++;

}
Yash Modi
2022BCSE051

cout<<"The position of the mid value is :"<<mid<<" and the data value is :"<<temp->data;

int main() {

node* head = new node(11);

insert_at_tail(20, head);

insert_at_tail(31, head);

insert_at_tail(49, head);

insert_at_tail(50, head);

insert_at_tail(69, head);

show_list(head);

return 0;

Q6 Write a function to find the intersection of two singly linked lists. If the lists do not

intersect, return null.

#include<bits/stdc++.h>

using namespace std;

class node{

public:

int data;

node* next;

node(int data){

this->data = data;

next = NULL;

};

void insert_at_tail(int data, node* &head){

node* temp = head;

while(temp->next != NULL){

temp = temp->next;

node* n = new node(data);


Yash Modi
2022BCSE051

temp->next = n;

int size_checker(node* head){

int count=0;

while(head!=NULL){

head=head->next;

count++;

return count;

void intersection(node* head1, node* head2){

int flag=0;

int count=abs(size_checker(head1)-size_checker(head2));

if(size_checker(head1)>size_checker(head2)){

while(count!=0){

head1=head1->next;

count--;

while((head1 && head2)){

if(head1==head2){

flag=1;

break;

head1=head1->next;

head2=head2->next;

else{

while(count!=0){

head2=head2->next;

count--;

while((head1 && head2)){


Yash Modi
2022BCSE051

if(head1==head2){

flag=1;

break;

head1=head1->next;

head2=head2->next;

if(!flag)

cout<<"No intersection";

else

cout<<"Intersection exists";

int main() {

node* head1 = new node(1);

node* head2 = new node(2);

node* commonNode = new node(10);

head1->next = commonNode;

head2->next = commonNode;

insert_at_tail(20, head1);

insert_at_tail(30, head2);

intersection(head1, head2);

return 0;

Q7 Write an O(n) time function to determine if a single linked list is a palindrome.

#include<bits/stdc++.h>

using namespace std;

class node{

public:

int data;

node* next;

node(int data){

this->data = data;
Yash Modi
2022BCSE051

next = NULL;

};

void insert_at_tail(int data, node* &head){

node* temp = head;

while(temp->next != NULL){

temp = temp->next;

node* n = new node(data);

temp->next = n;

void show_list(node* head){

while(head != NULL){

cout << head->data << " ";

head = head->next;

cout << endl;

void reversal(node* head, node* &dummy) {

if(!head)

return;

node* temp = new node(head->data);

temp->next = dummy;

dummy = temp;

reversal(head->next, dummy);

void pallindrome(node* head, node* dummy){

int flag=1;

while(dummy->next){

if(head->data==dummy->data)

flag=0;

else{

flag=1;

}
Yash Modi
2022BCSE051

head=head->next;

dummy=dummy->next;

if(flag==0)

cout<<"Pallindrome exists";

else{

cout<<"NO palindrome";

int main() {

node* head = new node(10);

insert_at_tail(2, head);

insert_at_tail(1, head);

insert_at_tail(1, head);

insert_at_tail(2, head);

insert_at_tail(1, head);

node* dummy= new node(0);

reversal(head,dummy);

pallindrome(head,dummy);

return 0;

Q8 Define the function moveToFront(struct node *head) to move a last node to the front of a

single linked list.

#include<bits/stdc++.h>

using namespace std;

class node{

public:

int data;

node* next;

node(int data){

this->data = data;

next = NULL;
Yash Modi
2022BCSE051

};

void insert_at_tail(int data, node* &head){

node* temp = head;

while(temp->next != NULL){

temp = temp->next;

node* n = new node(data);

temp->next = n;

void show_list(node* head){

while(head != NULL){

cout << head->data << " ";

head = head->next;

cout << endl;

void tail_to_head(node* &head){

node* temp=head;

while(temp->next->next!=NULL){

temp=temp->next;

temp->next->next=head;

head=temp->next;

temp->next=NULL;

int main() {

node* head = new node(11);

insert_at_tail(20, head);

insert_at_tail(31, head);

insert_at_tail(49, head);

insert_at_tail(50, head);

insert_at_tail(69, head);
Yash Modi
2022BCSE051

tail_to_head(head);

show_list(head);

Q9 Write a program to check if the list is in non-decreasing order or not.

#include <bits/stdc++.h>

using namespace std;

class node {

public:

int data;

node* next;

node(int data) {

this->data = data;

next = NULL;

};

void insert_at_tail(int data, node* &head) {

if (head == NULL) {

head = new node(data);

return;

node* temp = head;

while (temp->next != NULL) {

temp = temp->next;

node* n = new node(data);

temp->next = n;

void show_list(node* head) {

while (head != NULL) {

cout << head->data << " ";

head = head->next;

cout << endl;

}
Yash Modi
2022BCSE051

bool isNonDecreasing(node* head) {

if (head == NULL || head->next == NULL) {

return true;

node* current = head;

while (current->next != NULL) {

if (current->data > current->next->data) {

return false;

current = current->next;

return true;

void non_decreasing(node* head) {

if (isNonDecreasing(head)) {

cout << "Yes" << endl;

} else {

cout << "No" << endl;

int main() {

node* head = new node(11);

insert_at_tail(20, head);

insert_at_tail(31, head);

insert_at_tail(49, head);

insert_at_tail(50, head);

insert_at_tail(69, head);

cout << "Is the list in non-decreasing order? ";

non_decreasing(head);

return 0;

}
Yash Modi
2022BCSE051

WEEK 6

08-04-2024

Stack and Queues

Aim:

Implement the operations on Stack and Queue data structures.

Q1 Implement a static stack using an array with push, pop, peek, peep, isEmpty, size, and display operations.

#include<iostream>

using namespace std;

class Stack{

public:

int data;

Stack* next;

Stack(int data1){data=data1;next=NULL;}

Stack* top=NULL;

void push(int data){

Stack* temp=new Stack(data);

if(temp==NULL){cout<<"Stack Overflow"<<endl;}

temp->data=data;

temp->next=top;

top=temp;

void pop(){

Stack* temp;

if(top==NULL){cout<<"Stack Underflow"<<endl;}

temp=top;

top=top->next;

delete temp;

int peek(){

if(top==NULL){cout<<"Stack underflow"<<endl;return -1;}

return top->data;

int peep(int i){

Stack* temp=top;

if(temp==NULL){return -1;}
Yash Modi
2022BCSE051

if(i==1){return top->data;}

int count=0;

while(temp!=NULL){

count++;

if(count==i){return temp->data;}

temp=temp->next;

return -1;

bool isEmpty(){if(top==NULL){return true;}else{return false;}}

int size(){

int count=0;

Stack* temp=top;

while(temp!=NULL){count++;temp=temp->next;}

return count;

void display(){

Stack* temp=top;

if(top==NULL){cout<<"Stack Underflow"<<endl;}

while(temp!=NULL){cout<<temp->data<<" ";temp=temp->next;}

cout<<endl;

};

int main(){

Stack s(100);

[Link](1);[Link](5);[Link](10);

cout<<[Link]()<<endl;

[Link]();

cout<<[Link]()<<endl;

cout<<"Size of Stack : "<<[Link]();

return 0;

}
Yash Modi
2022BCSE051

Q2 Write a program for the dynamic implementation of stack using a single linked list with the

above functionalities.

#include<iostream>

using namespace std;

class Stack{

public:

int data;

Stack* next;

Stack(int data1) {data=data1;next=NULL;}

Stack* top=NULL;

void push(int data) {

Stack* temp=new Stack(data);

if(temp==NULL){cout<<"Stack Overflow"<<endl;}

temp->data=data;

temp->next=top;

top=temp;

void pop() {

Stack* temp;

if(top==NULL){cout<<"Stack Underflow"<<endl;}

temp=top;

top=top->next;

delete temp;

int peek() {

if(top==NULL){cout<<"Stack underflow"<<endl;return -1;}

return top->data;

int peep(int i) {

Stack* temp=top;

if(temp==NULL)return -1;

if(i==1)return top->data;

int count=0;

while(temp!=NULL){count++;if(count==i)return temp->data;temp=temp->next;}

return -1;
Yash Modi
2022BCSE051

bool isEmpty(){if(top==NULL){return true;}else{return false;}}

int size(){int count=0;Stack* temp=top;while(temp!=NULL){count++;temp=temp->next;}return count;}

void display(){Stack* temp=top;if(top==NULL){cout<<"Stack Underflow"<<endl;}while(temp!=NULL){cout<<temp-


>data<<" ";temp=temp->next;}cout<<endl;}

};

int main() {

Stack s(NULL);

[Link](1);[Link](5);[Link](10);

cout<<[Link]()<<endl;

[Link]();

cout<<[Link]()<<endl;

cout<<"Size of Stack : "<<[Link]();

return 0;}

Q3 Write a program for the static implementation of a circular queue using an array with enqueue, dequeue, front, isEmpty,
and size operations.

#include<bits/stdc++.h>

using namespace std;

class Queue{

public:

int *ar;

int size;

int front,rear;

Queue(int size){

this->size=size;

ar= new int[size];

front=0;

rear=0;

void enqueue(int data){

rear=(rear+1)%size;
Yash Modi
2022BCSE051

if(front==rear){cout<<"Queue, Overflow"<<endl;if(rear==0)rear=size-1;else rear-=1;}

else{ar[rear]=data;}

int dqueue(){

if(front==rear)cout<<"Queue, Underflow"<<endl;

else{front=(front+1)%size;int temp=ar[front];return temp;}

void display(){

if(front==rear){cout<<"Queue is empty"<<endl;}

else{for(int i=front+1;i<=rear;i++){cout<<ar[i]<<" ";}cout<<endl;}

};

int main() {

Queue q(8);

[Link](1);[Link](2);[Link](3);[Link](4);[Link](5);[Link](6);[Link](7);[Link]();

[Link]();[Link]();[Link]();[Link]();[Link]();

return 0;

Q4 Write a program for the dynamic implementation of a queue using a single linked list with the

above functionalities.

#include <bits/stdc++.h>

using namespace std;

class Queue {

public:

int data;

Queue* next;

Queue(int data) {this->data = data;next = nullptr;}

Queue* front = nullptr;

void enqueue(int data) {

Queue* newNode = new Queue(data);

if (front == nullptr) {front = newNode;newNode->next = newNode;}

else {Queue* temp = front;while (temp->next != front) {temp = temp->next;}

temp->next = newNode;newNode->next = front;}


Yash Modi
2022BCSE051

int dequeue() {

if (front == nullptr) {cout << "Queue Underflow!" << endl;return -1;}

int data = front->data;if (front->next == front) {delete front;front = nullptr;}

else {Queue* temp = front;while (temp->next != front) {temp = temp->next;}

Queue* firstNode = front;front = front->next;temp->next = front;delete firstNode;}

return data;

int peek() {

if (front == nullptr) {cout << "Queue is empty." << endl;return -1;}

return front->data;

bool isEmpty() {return front == nullptr;}

void display() {

if (front == nullptr) {cout << "Queue is empty." << endl;return;}

Queue* temp = front;do {cout << temp->data << " ";temp = temp->next;} while (temp != front);

cout << endl;

};

int main() {

Queue q(1);[Link](10);[Link](20);[Link](30);[Link](40);[Link]();

cout << "Peeked element: " << [Link]() << endl;[Link]();[Link]();[Link]();

return 0;

You might also like