0% found this document useful (0 votes)
23 views36 pages

Oop Practicals 1-14

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

Oop Practicals 1-14

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

INDEX

LIST OF EXPERIMENTS
(University Curriculum)

S.No. NAME OF THE EXPERIMENT PAGE.NO


1 Design C++ classes with static members, methods with default arguments, and 1-3
friend functions. (For example, design matrix and vector classes with static
allocation, and a friend function to do matrix-vector multiplication).
2 Implement Matrix class with dynamic memory allocation and necessary methods. 4-6
Give proper constructor, destructor, copy constructor, and overloading of the
assignment operator.
3 Implement complex number class with necessary operator overloading and type 7-8
conversions such as integer to complex, double to complex, complex to double
etc.
4 Overload the new and delete operators to provide a custom dynamic allocation of 9-10
memory
5 Develop C++ class hierarchy for various types of inheritances 11-13
6 Design a simple test application to demonstrate dynamic 14-15
polymorphism and RTTI.
7 Develop a template of the linked-list class and its methods 16-18
8 Develop templates of standard sorting algorithms such as 19-20
bubble sort, insertion sort and quick sort.
9 Design stack and queue classes with necessary exception 21-23
handling.
10 Write a C++ program that randomly generates complex 24-26
numbers (use previously designed Complex class) and write
them two per line in a file along with an operator (+, -, *, or /).
The numbers are written to file in the format (a + ib). Write
another program to read one line at a time from this file,
perform the
(BEYOND SYLLABUS)

S.No. NAME OF THE EXPERIMENT PAGE.NO


1 Write a C++ program to implement the stack ADT using an array 28-29
2 Write a C++ program to implement the Queue ADT using an array 30-31
3 Write C++ programs for implementing the Quick sort method. 32-33
4 Write C++ programs for implementing the Merge sort method. 34-25
(UNIVERSITY CURRICULUM)
EXPERIMENT NO. 1

AIM: - Design C++ classes with static members, methods with default arguments, and
friend functions. (For example, design matrix and vector classes with static allocation, and a
friend function to do matrix-vector multiplication).

SOURCE CODE:

#include<iostream>
using namespace std;

class vector;
//Making class for matrix
class matrix{
public:
int m[3][3];
//Matrix input
void getmatrix(void){

int i,j;
cout<<"Enter element : ";
for(i=0;i<3;i++) //Loop for getting martix in m[i][j] form
{
for(j=0;j<3;j++)
{
cin>>m[i][j];
}
}
}
void dismatrix() //code to display matrix
{
int i, j;
cout<<"Show:\n";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<m[i][j];
}
cout<<"\n";
}
}

friend void multiply(matrix &m1, vector &v1);


};

class vector
{
public:
int v[10];

void getvector(int n){


int i;
for(i=0;i<n;i++)
{
cin>>v[i];
}
}

void disvector()
{
int i;
cout<<"Enter element od vector : ";
for(i=0;i<3;i++)
{
cout<<v[i]<<" ";
}
}
friend void multiply(matrix &m1, vector &v1);
};
void multiply(matrix &m1, vector &v1)
{

int ans[3], i, j;

cout<<"\nThe resultant matrix…\n";

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

ans[i]=0;

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

{
static int x,y;
x=m1.m[i][j];
y=v1.v[j];

ans[i]= x*y;
}

cout<<ans[i]<<"\t";

int main()
{

matrix m1;
vector v1;
m1.getmatrix(); //calling input method of matrix
m1.dismatrix(); //calling output method of matrix
v1.getvector(3); //calling input method of vector
v1.disvector(); //calling output method of vector
multiply(m1,v1);
return 0;

OUTPUT:
EXPERIMENT NO. 2

AIM: - Implement Matrix class with dynamic memory allocation and necessary methods. Give
proper constructor, destructor, copy constructor, and overloading of the assignment operator.

SOURCE CODE: -

#include <iostream>
using namespace std;

class Matrix {
private:
int** data;
int rows;
int cols;

public:
Matrix(int rows, int cols) : rows(rows), cols(cols) {
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols];
}
}

// Destructor
~Matrix() {
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;
}

// Copy constructor
Matrix(const Matrix &other) : rows(other.rows), cols(other.cols) {
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols];
for (int j = 0; j < cols; j++) {
data[i][j] = other.data[i][j];
}
}
}

// Assignment operator overloading


Matrix& operator=(const Matrix &other) {
if (this == &other) {
return *this;
}
// Delete current data
for (int i = 0; i < rows; i++) {
delete[] data[i];
}
delete[] data;

// Copy data from other


rows = other.rows;
cols = other.cols;
data = new int*[rows];
for (int i = 0; i < rows; i++) {
data[i] = new int[cols];
for (int j = 0; j < cols; j++) {
data[i][j] = other.data[i][j];
}
}

return *this;
}

void input() {
std::cout << "Enter matrix elements:" << std::endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cin >> data[i][j];
}
}
}

void print() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << data[i][j] << ' ';
}
cout <<endl;
}
}
};

int main() {
int rows, cols;
cout << "Enter the number of rows and columns for Matrix 1: ";
cin >> rows >> cols;

Matrix mat1(rows, cols);


mat1.input();

Matrix mat2(2, 2);


mat2.input();
Matrix mat3 = mat1;

cout << "Matrix 1:" << endl;


mat1.print();
cout << "Matrix 3 (Copy of Matrix 1):" << endl;
mat3.print();

mat2 = mat1;

cout << "Matrix 2 (Assigned from Matrix 1):" <<endl;


mat2.print();

return 0;
}

OUTPUT:
EXPERIMENT NO. 3

AIM: - Implement complex number class with necessary operator overloading and type
conversions such as integer to complex, double to complex, complex to double etc.

SOURCE CODE: -

#include <iostream>
using namespace std;

class Complex {
private:
double real;
double imaginary;

public:
Complex():real(0.0),imaginary(0.0) {}
Complex(double r,double i):real(r),imaginary(i) {}

Complex operator+(const Complex& other) {


return Complex(real + other.real, imaginary + other.imaginary);
}

Complex operator-(const Complex& other) {


return Complex(real - other.real, imaginary - other.imaginary);
}

Complex operator*(const Complex& other) {


return Complex(real * other.real - imaginary * other.imaginary,
real * other.imaginary + imaginary * other.real);
}

Complex(int integer) : real(static_cast<double>(integer)), imaginary(0.0) {}

Complex(double realPart) : real(realPart), imaginary(0.0) {}

operator double() const {


return real;
}

void display() {
if (imaginary >= 0)
std::cout << real << " + " << imaginary << "i" << std::endl;
else
std::cout << real << " - " << -imaginary << "i" << std::endl;
}
};

int main() {
Complex a(3, 2);
Complex b(1, -1);

Complex c = a + b;
Complex d = a - b;
Complex e = a * b;
c.display();
d.display();
e.display();
int integer = 5;
Complex f = integer;
double realNumber = 2.5;
Complex g = realNumber;
double realPart = static_cast<double>(a);
f.display();
g.display();
std::cout << "Real part of a: " << realPart << std::endl;
return 0;
}

OUTPUT:
EXPERIMENT NO. 4

AIM: - Overload the new and delete operators to provide a custom dynamic allocation of
memory

SOURCE CODE: -

#include<iostream>
#include<stdlib.h>
using namespace std;
class student
{
string name;
int age;
public:
student()
{
cout<<"constructor is called"<<endl;

}
student(string name,int age)
{
this->name = name;
this->age = age;

}
void display()
{
cout<<"name: "<<name<<endl;
cout<<"age: "<<age<<endl;

}
void* operator new(size_t size)
{
void* p = ::operator new(size);
return p;

}
void operator delete(void*p)
{
cout<<"overloading delete operation"<<endl;
free(p);
}

int main()
{
student* p = new student("yash",24);
p->display();
delete p;
}

OUTPUT:
EXPERIMENT NO. 5

AIM: - Develop C++ class hierarchy for various types of inheritances.

SOURCE CODE: -

Develop C++ class hierarchy for various types of inheritances

a. Single inheritance and multilevel inheritance

#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking...";
}
};
class BabyDog: public Dog
{
public:
void weep() {
cout<<"Weeping...";
}
};
int main(void) {
BabyDog d1;
d1.eat();
d1.bark();
d1.weep();
return 0;
}

OUTPUT:
b. Hierarchical Inheritance

#include <iostream>
using namespace std;
class Shape // Declaration of base class.
{
public:
int a;
int b;
void get_data(int n,int m)

{
a= n;
b = m;
}
};
class Rectangle : public Shape // inheriting Shape class

{
public:
int rect_area()
{
int result = a*b;
return result;
}
};
class Triangle : public Shape // inheriting Shape class
{
public:
int triangle_area()
{
float result = 0.5*a*b;
return result;
}
};
int main()
{
Rectangle r;
Triangle t;
int length,breadth,base,height;
std::cout << "Enter the length and breadth of a rectangle: " << std::endl;
cin>>length>>breadth;
r.get_data(length,breadth);
int m = r.rect_area();
std::cout << "Area of the rectangle is : " <<m<< std::endl;
std::cout << "Enter the base and height of the triangle: " << std::endl;
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
std::cout <<"Area of the triangle is : " << n<<std::endl;
return 0;
}

OUTPUT:
EXPERIMENT NO. 6

AIM: - Design a simple test application to demonstrate dynamic polymorphism and RTTI.

SOURCE CODE: -

A) Design a simple test application to demonstrate dynamic polymorphism and RTTI.

#include<iostream>
using namespace std;
class B // Base class
{

public:
virtual void Display(void) // virtual function
{
cout << "\n The member function Display( ) " ;
cout << "of the \"Base Class B\" is invoked \n" ;
}
};
class D1 : public B // First derived class
{
public:
void Display(void)
{
cout << "\n The member function Display( ) " ;
cout << "of the \"Derived Class D1\" is invoked \n" ;
}
};
class D2 : public B // Second derived class
{
public:
void Display(void)
{
cout << "\n The member function Display() " ;
cout << "of the \"Derived Class D2\" is invoked " ;
}
};

int main()
{
B* base_ptr ; // Pointer to the object of the base class

D1 der1_obj ; // Object of the first derived class D1


base_ptr = &der1_obj ; /* The address of the object der1_obj of the
first derived class D1 is assigned to the
pointer base_ptr of the base class B */
base_ptr->Display( ); // Accessing the member function Display( )

D2 der2_obj ; // Object of the second derived class D2


base_ptr = &der2_obj ; /* The address of the object der2_obj of the
second derived class D2 is assigned to the
pointer base_ptr of the base class B */
base_ptr->Display( ); // Accessing the member function Display( )
return 0;
}

OUTPUT:

B) Design a simple test application to demonstrate RTTi

#include <iostream>
using namespace std;

// Initialization of base class


class B {
virtual void fun() {}
};
// Initialization of Derived class
class D : public B {
};
// Driver Code
int main()
{
B* b = new D; // Base class pointer
D* d = dynamic_cast<D*>(b); // Derived class pointer
if (d != NULL)
cout << "works";
else
cout << "cannot cast B* to D*";
getchar();
return 0;
}

OUTPUT:
EXPERIMENT NO. 7

AIM: - Develop a template of the linked-list class and its methods.

SOURCE CODE: -

#include <iostream>
template <typename T>
class Node {
public:
T data;
Node* next;

Node(const T& value) : data(value), next(nullptr) {}


};
template <typename T>
class LinkedList {
private:
Node<T>* head;
public:
LinkedList() : head(nullptr) {}

~LinkedList() {
// Destructor to delete all nodes when the linked list is destroyed
clear();
}
void append(const T& value) {
Node<T>* newNode = new Node<T>(value);
if (!head) {
head = newNode;
} else {
Node<T>* current = head;
while (current->next) {
current = current->next;
}
current->next = newNode;
}
}
void prepend(const T& value) {
Node<T>* newNode = new Node<T>(value);
newNode->next = head;
head = newNode;
}
void remove(const T& value) {
if (!head) {
return; // Empty list, nothing to remove
}

if (head->data == value) {
Node<T>* temp = head;
head = head->next;
delete temp;
return;
}
Node<T>* current = head;
while (current->next && current->next->data != value) {
current = current->next;
}
if (current->next) {
Node<T>* temp = current->next;
current->next = current->next->next;
delete temp;
}
}
void display() const {
Node<T>* current = head;
while (current) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}

void clear() {
while (head) {
Node<T>* temp = head;
head = head->next;
delete temp;
}
}
};

int main() {
// Linked List example
LinkedList<int> myList;
myList.append(10);
myList.append(20);
myList.prepend(5);
myList.append(30);

std::cout << "Linked List: ";


myList.display();
myList.remove(20);

std::cout << "Linked List after removing 20: ";


myList.display();
myList.clear(); // Destructor is called implicitly when myList goes out of scope

return 0;
}
OUTPUT:
EXPERIMENT NO. 8

AIM: - Develop templates of standard sorting algorithms such as bubble


sort, insertion sort and quick sort.

SOURCE CODE: -

#include <iostream>
#include <vector>

// Template function to perform the Bubble Sort algorithm


template <typename T>
void bubbleSort(std::vector<T>& arr) {
int n = arr.size();
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
std::swap(arr[j], arr[j + 1]);
}
}
}
}

// Template function to perform the Selection Sort algorithm


template <typename T>
void selectionSort(std::vector<T>& arr) {
int n = arr.size();
for (int i = 0; i < n - 1; ++i) {
int minIndex = i;
for (int j = i + 1; j < n; ++j) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
std::swap(arr[i], arr[minIndex]);

}
}

// Template function to print the elements of a vector


template <typename T>
void printVector(const std::vector<T>& arr) {
for (const T& element : arr) {
std::cout << element << " ";
}
std::cout << std::endl;
}
int main() {
// Example usage of sorting algorithms with integers
std::vector<int> intArr = {64, 25, 12, 22, 11};

std::cout << "Original array: ";


printVector(intArr);
// Bubble Sort
bubbleSort(intArr);
std::cout << "Array after Bubble Sort: ";
printVector(intArr);

// Selection Sort
selectionSort(intArr);
std::cout << "Array after Selection Sort: ";
printVector(intArr);

return 0;
}

OUTPUT:
EXPERIMENT NO. 9

AIM: - Design stack and queue classes with necessary exception handling.

SOURCE CODE: -

#include <iostream>
#include <stdexcept>

// Stack class
template <typename T>
class Stack {
private:
static const int MAX_SIZE = 100;
T data[MAX_SIZE];
int top;
public:
Stack() : top(-1) {}

void push(const T& value) {


if (top == MAX_SIZE - 1) {
throw std::overflow_error("Stack overflow");
}
data[++top] = value;
}

T pop() {
if (isEmpty()) {
throw std::underflow_error("Stack underflow");
}
return data[top--];
}
bool isEmpty() const {
return top == -1;
}
};

// Queue class
template <typename T>
class Queue {
private:
static const int MAX_SIZE = 100;
T data[MAX_SIZE];
int front, rear;
public:
Queue() : front(-1), rear(-1) {}

void enqueue(const T& value) {


if (isFull()) {
throw std::overflow_error("Queue overflow");
}

if (isEmpty()) {
front = rear = 0;
} else {
rear = (rear + 1) % MAX_SIZE;
}

data[rear] = value;
}

T dequeue() {
if (isEmpty()) {
throw std::underflow_error("Queue underflow");
}

T value = data[front];
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % MAX_SIZE;
}
return value;
}

bool isEmpty() const {


return front == -1 && rear == -1;
}

bool isFull() const {


return (rear + 1) % MAX_SIZE == front;
}
};
int main() {
try {
// Stack example
Stack<int> myStack;
myStack.push(10);
myStack.push(20);
myStack.push(30);

while (!myStack.isEmpty()) {
std::cout << "Stack popped: " << myStack.pop() << std::endl;
}

// Queue example
Queue<std::string> myQueue;
myQueue.enqueue("First");
myQueue.enqueue("Second");
myQueue.enqueue("Third");
while (!myQueue.isEmpty()) {
std::cout << "Queue dequeued: " << myQueue.dequeue() << std::endl;
}
} catch (const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
}

return 0;
}

OUTPUT:
EXPERIMENT NO. 10

AIM: - Write a C++ program that randomly generates complex numbers (use previously designed
Complex class) and write them two per line in a file along with an operator (+, -, *, or /). The numbers
are written to file in the format (a + ib). Write another program to read one line at a time from this file,
perform the operations, and prints the results.

SOURCE CODE: -

#include <iostream>
#include <fstream>
#include <cstdlib> // For rand() and srand()
#include <ctime> // For time()

// Complex class definition


class Complex {
private:
double real;
double imag;

public:
Complex() : real(0.0), imag(0.0) {}
Complex(double r, double i) : real(r), imag(i) {}

// Overloaded operators for complex number arithmetic


Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}

Complex operator*(const Complex& other) const {


return Complex((real * other.real) - (imag * other.imag),
(real * other.imag) + (imag * other.real));
}

Complex operator/(const Complex& other) const {


double denominator = other.real * other.real + other.imag * other.imag;
if (denominator == 0) {
std::cerr << "Error: Division by zero." << std::endl;
exit(EXIT_FAILURE);
}
return Complex(((real * other.real) + (imag * other.imag)) / denominator,
((imag * other.real) - (real * other.imag)) / denominator);
}
// Function to display the complex number
friend std::ostream& operator<<(std::ostream& os, const Complex& c);
};
std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << "(" << c.real << " + " << c.imag << "i)";
return os;
}
int main() {
// Seed the random number generator
srand(static_cast<unsigned>(time(nullptr)));
// Generate random complex numbers and operators
const int numPairs = 5;
Complex numbers[numPairs][2];
char operators[numPairs] = {'+', '-', '*', '/'};
// Open file for writing
std::ofstream outputFile("complex_numbers.txt");

if (!outputFile.is_open()) {
std::cerr << "Error: Unable to open file for writing." << std::endl;
return EXIT_FAILURE;
}

// Generate random complex numbers and operators, write to file


for (int i = 0; i < numPairs; ++i) {
numbers[i][0] = Complex(rand() % 10, rand() % 10);
numbers[i][1] = Complex(rand() % 10, rand() % 10);
char op = operators[rand() % 4];
// Write complex numbers and operator to the file
outputFile << numbers[i][0] << " " << op << " " << numbers[i][1] << std::endl;
}

// Close the file


outputFile.close();
std::cout << "Complex numbers and operators written to file 'complex_numbers.txt'." << std::endl;

return 0;
}
Program 2 (ReadComplexFromFile.cpp):
#include <iostream>
#include <fstream>
#include "Complex.h" // Assuming the Complex class is defined in a separate header file

int main() {
// Open file for reading
std::ifstream inputFile("complex_numbers.txt");

if (!inputFile.is_open()) {
std::cerr << "Error: Unable to open file for reading." << std::endl;
return EXIT_FAILURE;
}
Complex num1, num2, result;
char op;

// Read one line at a time from the file


while (inputFile >> num1 >> op >> num2) {
// Perform the corresponding operation based on the operator
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
std::cerr << "Error: Invalid operator." << std::endl;
return EXIT_FAILURE;
}
// Display the result
std::cout << num1 << " " << op << " " << num2 << " = " << result << std::endl;
}

// Close the file


inputFile.close();

return 0;
}
(BEYOND SYLLABUS)

EXPERIMENT NO. 1

AIM:- Write a C++ program to implement the stack ADT using an array

SOURCE CODE:-
#include <iostream>

#define MAX_SIZE 100 // Maximum size of the stack

class Stack {
private:
int top; // Index of the top element in the stack
int arr[MAX_SIZE]; // Array to store stack elements

public:
Stack() {
top = -1; // Initialize top to -1 indicating an empty stack
}

// Function to push an element onto the stack


void push(int value) {
if (top == MAX_SIZE - 1) {
std::cout << "Stack Overflow! Cannot push more elements." << std::endl;
return;
}
arr[++top] = value; // Increment top and then add the value to the top of the stack
}

// Function to pop an element from the stack


int pop() {
if (isEmpty()) {
std::cout << "Stack Underflow! Cannot pop from an empty stack." << std::endl;
return -1; // Return -1 to indicate failure
}
return arr[top--]; // Return the top element and then decrement top
}

// Function to check if the stack is empty


bool isEmpty() {
return top == -1;
}

// Function to return the top element without removing it


int peek() {
if (isEmpty()) {
std::cout << "Stack is empty!" << std::endl;
return -1; // Return -1 to indicate failure
}
return arr[top];
}
};

int main() {
Stack myStack;

myStack.push(10);
myStack.push(20);
myStack.push(30);

std::cout << "Top element of the stack: " << myStack.peek() << std::endl;

std::cout << "Popping elements from the stack: ";


while (!myStack.isEmpty()) {
std::cout << myStack.pop() << " ";
}
std::cout << std::endl;

return 0;
}

OUTPUT:
EXPERIMENT NO. 2

AIM:- Write a C++ program to implement the Queue ADT using an array

SOURCE CODE:-
#include <iostream>

#define MAX_SIZE 100 // Maximum size of the queue

class Queue {
private:
int front; // Index of the front element in the queue
int rear; // Index of the rear element in the queue
int arr[MAX_SIZE]; // Array to store queue elements

public:
Queue() {
front = -1; // Initialize front and rear to -1 indicating an empty queue
rear = -1;
}

// Function to enqueue (add) an element to the queue


void enqueue(int value) {
if (rear == MAX_SIZE - 1) {
std::cout << "Queue Overflow! Cannot enqueue more elements." << std::endl;
return;
}
if (isEmpty()) {
front = 0; // If the queue is empty, set front to 0
}
arr[++rear] = value; // Increment rear and then add the value to the rear of the queue
}

// Function to dequeue (remove) an element from the queue


int dequeue() {
if (isEmpty()) {
std::cout << "Queue Underflow! Cannot dequeue from an empty queue." << std::endl;
return -1; // Return -1 to indicate failure
}
int value = arr[front++]; // Remove and return the front element, then increment front
if (front > rear) {
front = rear = -1; // If the queue becomes empty after dequeue, reset front and rear
}
return value;
}

// Function to check if the queue is empty


bool isEmpty() {
return front == -1;
}

// Function to return the front element without removing it


int peek() {
if (isEmpty()) {
std::cout << "Queue is empty!" << std::endl;
return -1; // Return -1 to indicate failure
}
return arr[front];
}
};

int main() {
Queue myQueue;

myQueue.enqueue(10);
myQueue.enqueue(20);
myQueue.enqueue(30);

std::cout << "Front element of the queue: " << myQueue.peek() << std::endl;

std::cout << "Dequeueing elements from the queue: ";


while (!myQueue.isEmpty()) {
std::cout << myQueue.dequeue() << " ";
}
std::cout << std::endl;

return 0;
}

OUTPUT:
EXPERIMENT NO. 3

AIM:- Write C++ programs for implementing the Quick sort method.

SOURCE CODE:-

#include <iostream>
#include <vector>

// Function to partition the array and return the index of the pivot element
int partition(std::vector<int>& arr, int low, int high) {
int pivot = arr[high]; // Choose the last element as the pivot
int i = low - 1; // Index of the smaller element

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


// If current element is smaller than or equal to the pivot
if (arr[j] <= pivot) {
i++; // Increment index of smaller element
std::sp(arr[i], arr[j]); // Swap arr[i] and arr[j]
}
}
std::swap(arr[i + 1], arr[high]); // Swap arr[i+1] and arr[high] (pivot)
return i + 1; // Return the partitioning index
}

// Function to perform Quick Sort


void quickSort(std::vector<int>& arr, int low, int high) {
if (low < high) {
// Partition the array and get the partitioning index
int pi = partition(arr, low, high);

// Recursively sort elements before partition and after partition


quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

// Utility function to print an array


void printArray(const std::vector<int>& arr) {
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
}

int main() {
std::vector<int> arr = {12, 8, 5, 14, 7, 3, 9};

std::cout << "Original array: ";


printArray(arr);

// Perform Quick Sort


quickSort(arr, 0, arr.size() - 1);

std::cout << "Sorted array: ";


printArray(arr);
return 0;
}

OUTPUT:
EXPERIMENT NO. 4

AIM:- Write C++ program for implementing the Merge sort method.

SOURCE CODE:-

#include <iostream>
#include <vector>

// Merge function to merge two sorted subarrays into one sorted array
void merge(std::vector<int>& arr, int low, int mid, int high) {
int n1 = mid - low + 1; // Size of the left subarray
int n2 = high - mid; // Size of the right subarray

// Create temporary arrays to hold the left and right subarrays


std::vector<int> left(n1);
std::vector<int> right(n2);

// Copy data to temporary arrays left[] and right[]


for (int i = 0; i < n1; i++)
left[i] = arr[low + i];
for (int j = 0; j < n2; j++)
right[j] = arr[mid + 1 + j];

// Merge the temporary arrays back into arr[low..high]


int i = 0; // Initial index of left subarray
int j = 0; // Initial index of right subarray
int k = low; // Initial index of merged subarray

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


if (left[i] <= right[j]) {
arr[k] = left[i];
i++;
} else {
arr[k] = right[j];
j++;
}
k++;
}

// Copy the remaining elements of left[], if any


while (i < n1) {
arr[k] = left[i];
i++;
k++;
}

// Copy the remaining elements of right[], if any


while (j < n2) {
arr[k] = right[j];
j++;
k++;
}
}
// Merge Sort function to sort the array
void mergeSort(std::vector<int>& arr, int low, int high) {
if (low < high) {
// Find the middle point
int mid = low + (high - low) / 2;

// Recursively sort the left and right halves


mergeSort(arr, low, mid);
mergeSort(arr, mid + 1, high);

// Merge the sorted halves


merge(arr, low, mid, high);
}
}

// Utility function to print an array


void printArray(const std::vector<int>& arr) {
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
}

int main() {
std::vector<int> arr = {12, 8, 5, 14, 7, 3, 9};

std::cout << "Original array: ";


printArray(arr);

// Perform Merge Sort


mergeSort(arr, 0, arr.size() - 1);

std::cout << "Sorted array: ";


printArray(arr);

return 0;
}

OUTPUT:

You might also like