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

Projects and Assignment

The document discusses three lab reports on data structures and algorithms. The first report demonstrates basic array operations in C++. The second report implements linear and binary search on an array. The third report adds sorting algorithms and expands the menu options to include searching and sorting of arrays.

Uploaded by

hadia abid
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Projects and Assignment

The document discusses three lab reports on data structures and algorithms. The first report demonstrates basic array operations in C++. The second report implements linear and binary search on an array. The third report adds sorting algorithms and expands the menu options to include searching and sorting of arrays.

Uploaded by

hadia abid
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

Data Structures and Algorithms

Lab report
Submitted By
HADIA ABID (BSAI-298)
Ajiya Asif (BSAI-057)

Submitted to
Ayesha Jarral

Lab task 1:
#include <iostream>
using namespace std;

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


cout << "Array elements: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

int findSum(int arr[], int size) {


int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}

double findAverage(int arr[], int size) {


int sum = findSum(arr, size);
return static_cast<double>(sum) / size;
}

int findMax(int arr[], int size) {


int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}

int main() {
const int SIZE = 5;
int arr[SIZE];
cout << "Enter 5 integers:" << endl;
for (int i = 0; i < SIZE; i++) {
cout << "Element " << (i + 1) << ": ";
cin >> arr[i];
}
printArray(arr, SIZE);
int sum = findSum(arr, SIZE);
cout << "Sum of array elements: " << sum << endl;
double average = findAverage(arr, SIZE);
cout << "Average of array elements: " << average << endl;
int max = findMax(arr, SIZE);
cout << "Maximum value in the array: " << max << endl;

return 0;
}
Output:

Objective: Demonstrate basic operations on arrays in C++.


Program Structure:
Function Definitions:
printArray: Prints all elements of the array.
findSum: Calculates and returns the sum of all elements in the array.
findAverage: Calculates and returns the average of the array elements.
findMax: Finds and returns the maximum value in the array.
Main Function: Initializes an array, populates it with user inputs, calls the defined functions to perform
the required operations, and displays the results.

Lab 2: Linear and Binary Search


#include <iostream>
using namespace std;

int linearSearch(int arr[], int size, int key) {


for (int i = 0; i < size; ++i) {
if (arr[i] == key) {
return i;
}
}
return -1;
}

int binarySearch(int arr[], int size, int key) {


int low = 0, high = size - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}

int main() {
int arr[] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int size = sizeof(arr) / sizeof(arr[0]);

while (true) {
cout << "Menu:\n1. Linear Search\n2. Binary Search\n3. Exit\nEnter your choice: ";
int choice;
cin >> choice;

switch (choice) {
case 1: {
int key;
cout << "Enter the element to search: ";
cin >> key;
int result = linearSearch(arr, size, key);
if (result != -1) {
cout << "Element " << key << " found at index " << result << "." << endl;
} else {
cout << "Element " << key << " not found in the array." << endl;
}
break;
}
case 2: {
int key;
cout << "Enter the element to search: ";
cin >> key;
int result = binarySearch(arr, size, key);
if (result != -1) {
cout << "Element " << key << " found at index " << result << "." << endl;
} else {
cout << "Element " << key << " not found in the array." << endl;
}
break;
}
case 3:
cout << "Exiting the program." << endl;
return 0;
default:
cout << "Invalid choice. Please choose 1, 2, or 3." << endl;
}
}
return 0;
}
Output:

Report: Menu-Driven Array Search Program


Introduction: User-friendly interface for searching elements within an array using C++. Users can choose
between linear search and binary search. The program processes the selected search operation on a
predefined array and displays the result.
Program Overview: Main menu with options for different search algorithms: Linear Search, Binary
Search, and Exit.
Program Execution:
 Linear Search: Prompts for an element and performs linear search on the array.
 Binary Search: Prompts for an element and performs binary search on the array.
 Exiting the Program: Gracefully terminates upon selecting the exit option.
Conclusion: Simplifies the process of conducting searches on an array using either linear or binary
search algorithms. Demonstrates fundamental C++ programming concepts.

Lab report 3:
#include <iostream>
using namespace std;

int linearSearch(int arr[], int size, int key) {


for (int i = 0; i < size; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}

int binarySearch(int arr[], int size, int key) {


int left = 0;
int right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) {
return mid;
}
if (arr[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}

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


for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
}

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


for (int i = 0; i < size - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
swap(arr[i], arr[minIndex]);
}
}

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


for (int i = 1; i < size; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

int main() {
int choice;
const int size = 10;
int arr[size] = {12, 45, 23, 8, 14, 31, 6, 57, 34, 19};

do {
cout << "Menu:\n1. Linear Search\n2. Binary Search\n3. Bubble Sort\n4. Selection Sort\n5.
Insertion Sort\n6. Exit\nEnter your choice: ";
cin >> choice;

switch (choice) {
case 1: {
int key;
cout << "Enter the element to search: ";
cin >> key;
int result = linearSearch(arr, size, key);
if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not found in the array." << endl;
}
break;
}
case 2: {
int key;
cout << "Enter the element to search: ";
cin >> key;
bubbleSort(arr, size);
int result = binarySearch(arr, size, key);
if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not found in the array." << endl;
}
break;
}
case 3:
bubbleSort(arr, size);
cout << "Array sorted using Bubble Sort." << endl;
break;
case 4:
selectionSort(arr, size);
cout << "Array sorted using Selection Sort." << endl;
break;
case 5:
insertionSort(arr, size);
cout << "Array sorted using Insertion Sort." << endl;
break;
case 6:
cout << "Exiting the program." << endl;
break;
default:
cout << "Invalid choice. Please choose a valid option." << endl;
}

cout << "Sorted array: ";


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

} while (choice != 6);

return 0;
}
Output:

Lab Report 4:
Stack:
#include <iostream>
#include <stack>
using namespace std;

class StackProgram {
private:
stack<int> myStack;

public:
void pushElement(int value) {
myStack.push(value);
cout << "Pushed " << value << " onto the stack." << endl;
}

void popElement() {
if (!myStack.empty()) {
cout << "Popped " << myStack.top() << " from the stack." << endl;
myStack.pop();
} else {
cout << "Stack is empty. Cannot pop." << endl;
}
}
void displayStack() {
if (!myStack.empty()) {
stack<int> tempStack = myStack;
cout << "Stack contents from top to bottom: ";
while (!tempStack.empty()) {
cout << tempStack.top() << " ";
tempStack.pop();
}
cout << endl;
} else {
cout << "Stack is empty." << endl;
}
}
};

int main() {
StackProgram stackObj;
int choice, value;

while (true) {
cout << "\nStack Menu:\n";
cout << "1. Push an element\n";
cout << "2. Pop an element\n";
cout << "3. Display the stack\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter an element to push: ";
cin >> value;
stackObj.pushElement(value);
break;
case 2:
stackObj.popElement();
break;
case 3:
stackObj.displayStack();
break;
case 4:
cout << "Exiting the program." << endl;
return 0;
default:
cout << "Invalid choice. Please enter a valid option." << endl;
}
}

return 0;
}
Ouput:

Code Overview:
Your C++ code implements a basic stack data structure using the standard library's stack container.
Below is a concise breakdown of its components:
1. Class Definition:
 The StackProgram class encapsulates stack operations.
 It contains a private member myStack of type stack<int> for storing integer elements.
2. Public Member Functions:
 pushElement(int value): Pushes the given value onto the stack and prints a confirmation
message.
 popElement(): Pops the top element from the stack if it's not empty and prints its value. If the
stack is empty, it prints a message indicating so.
 displayStack(): Displays the contents of the stack from top to bottom. If the stack is empty, it
prints a message indicating so.
3. Main Function:
 The main function handles user interaction through a menu-driven interface.
 It repeatedly prompts the user for input until the exit option is chosen.
4. Input Validation:
 Input validation is limited; the code does not handle non-integer inputs gracefully.
5. Style and Conventions:
 Class names conventionally start with an uppercase letter (StackProgram), which is followed.
 CamelCase is used for function names, ensuring consistency.
6. Comments:
 The code lacks comments for clarification, which could improve readability and maintainability.
Conclusion: Your code provides a functional implementation of a stack with essential functionalities.
However, improvements in input validation, code formatting, and commenting could enhance its
readability and robustness.

Lab report 5:
#include <iostream>
using namespace std;

const int MAX_SIZE = 100;

class LinearQueue {
private:
int arr[MAX_SIZE];
int front, rear;

public:
LinearQueue() : front(-1), rear(-1) {}

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

bool isFull() {
return (rear == MAX_SIZE - 1);
}

void enqueue(int data) {


if (isFull()) {
cout << "Queue is full. Unable to enqueue." << endl;
return;
}

if (isEmpty()) {
front = 0;
}

arr[++rear] = data;
cout << "Enqueued " << data << " into the queue." << endl;
}

void dequeue() {
if (isEmpty()) {
cout << "Queue is empty. Unable to dequeue." << endl;
return;
}

int data = arr[front];


cout << "Dequeued " << data << " from the queue." << endl;

if (front == rear) {
front = rear = -1;
} else {
front++;
}
}

void displayFront() {
if (isEmpty()) {
cout << "Queue is empty. No front element." << endl;
} else {
cout << "Front element: " << arr[front] << endl;
}
}

void displayQueue() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
} else {
cout << "Queue elements: ";
for (int i = front; i <= rear; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
}
};

int main() {
LinearQueue queue;
int choice, data;

do {
cout << "\nQueue Menu:\n";
cout << "1. Enqueue\n";
cout << "2. Dequeue\n";
cout << "3. Display Front\n";
cout << "4. Display Queue\n";
cout << "5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter data to enqueue: ";
cin >> data;
queue.enqueue(data);
break;
case 2:
queue.dequeue();
break;
case 3:
queue.displayFront();
break;
case 4:
queue.displayQueue();
break;
case 5:
cout << "Exiting program. Goodbye!\n";
break;
default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 5);

return 0;
}
Output:

Linear Queue Implementation in C++


1. Introduction: The provided C++ code demonstrates the implementation of a linear queue using
an array-based approach. The program allows users to perform standard queue operations such
as enqueueing, dequeuing, and displaying queue elements.
2. Code Structure:
 The LinearQueue class encapsulates the queue data structure and operations.
 Key functions include enqueue, dequeue, displayFront, and displayQueue.
 The main function serves as the user interface, providing a menu-driven approach for
interacting with the queue.
3. Queue Operations:
 Enqueue: Adds an element to the rear of the queue.
 Dequeue: Removes an element from the front of the queue.
 Display Front: Displays the front element of the queue without dequeuing it.
 Display Queue: Shows all elements currently in the queue.
4. User Interaction:
 Users interact with the program through a menu interface.
 Input prompts guide users to perform specific queue operations.
 Error messages notify users of any invalid actions, such as dequeueing from an empty
queue or enqueueing when the queue is full.
5. Conclusion: The linear queue implementation provides a simple yet effective way to manage
data in a FIFO (First-In-First-Out) manner. The code offers a foundational understanding of
queue data structures and can be extended or modified for various applications where FIFO
processing is required.

Lab report 6:
#include <iostream>
using namespace std;

const int MAX_SIZE = 100;

class CircularQueue {
private:
int arr[MAX_SIZE];
int front, rear;

public:
CircularQueue() : front(-1), rear(-1) {}

bool isEmpty() {
return (front == -1 && rear == -1);
}
bool isFull() {
return (front == (rear + 1) % MAX_SIZE);
}

void enqueue(int data) {


if (isFull()) {
cout << "Queue is full. Unable to enqueue." << endl;
return;
}

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

arr[rear] = data;
cout << "Enqueued " << data << " into the queue." << endl;
}

void dequeue() {
if (isEmpty()) {
cout << "Queue is empty. Unable to dequeue." << endl;
return;
}

int data = arr[front];


cout << "Dequeued " << data << " from the queue." << endl;
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % MAX_SIZE;
}
}

void displayFront() {
if (isEmpty()) {
cout << "Queue is empty. No front element." << endl;
} else {
cout << "Front element: " << arr[front] << endl;
}
}

void displayQueue() {
if (isEmpty()) {
cout << "Queue is empty." << endl;
} else {
cout << "Queue elements: ";
int i = front;
while (true) {
cout << arr[i] << " ";
if (i == rear) break;
i = (i + 1) % MAX_SIZE;
}
cout << endl;
}
}
};

int main() {
CircularQueue queue;
int choice, data;

do {
cout << "\nCircular Queue Menu:\n";
cout << "1. Enqueue\n";
cout << "2. Dequeue\n";
cout << "3. Display Front\n";
cout << "4. Display Queue\n";
cout << "5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter data to enqueue: ";
cin >> data;
queue.enqueue(data);
break;
case 2:
queue.dequeue();
break;
case 3:
queue.displayFront();
break;
case 4:
queue.displayQueue();
break;
case 5:
cout << "Exiting program. Goodbye!\n";
break;
default:
cout << "Invalid choice. Please try again.\n";
}
} while (choice != 5);

return 0;
}
Output:

Circular Queue Implementation in C++


1. Introduction: This C++ program demonstrates the implementation of a circular queue, a
variant of the linear queue where the last element is connected to the first element, forming a
circular arrangement. The circular queue allows FIFO (First-In-First-Out) processing of data.
2. Code Structure:
 The CircularQueue class encapsulates the circular queue data structure and its
operations.
 Key functions include enqueue, dequeue, displayFront, and displayQueue.
 The main function serves as the user interface, providing a menu-driven approach for
interacting with the circular queue.
3. Queue Operations:
 Enqueue: Adds an element to the rear of the circular queue.
 Dequeue: Removes an element from the front of the circular queue.
 Display Front: Displays the front element of the circular queue without dequeuing it.
 Display Queue: Shows all elements currently in the circular queue.
4. Circular Behavior:
 Circular queue operations ensure that elements wrap around the array structure when
the rear index reaches the end, thus creating a circular arrangement.
5. User Interaction:
 Users interact with the program through a menu interface.
 Input prompts guide users to perform specific circular queue operations.
 Error messages notify users of any invalid actions, such as dequeueing from an empty
queue or enqueueing when the queue is full.
6. Conclusion: The circular queue implementation provides an efficient way to manage data in a
FIFO manner while utilizing space effectively. The code offers a foundational understanding of
circular queue data structures and can be extended or modified for various applications where
circular processing of data is required.
Lab 7: Insertion in Linked List

Objectives

To learn about linked list operations including insertion from beginning , middle, end and
display.

Linked List

• Linked List is a linear data structure which is made up of nodes connected by pointers.

• Dynamic Data Structure

• Each node has two parts:

Data: To store information (data)

Link: To store address of next node


Lab Task

#include <iostream>

Using namespace std;

Struct node

Int info;

Node *link;

};

Node*head= NULL;

Int count = 0;

Void insertBeg(int data)

Node*newNode = new node;

newNode->info= data;

newNode->link = head;
head= newNode;

count++;

Void insertmiddle(int data)

Node* newNode = new node;

newNode->info = data;

newNode->link = NULL;

if (head == NULL)

Head = newNode;

Else

{ int mid= count/2;

Node*temp=head;
Int c= 1;

While (c!= mid)

{temp =temp->link;

C++;

newNode->link =temp->link;

temp->link =newNode;}

count++;

Void insertend(int data)

Node* newNode =new node;

newNode->info= data;

newNode->link = NULL;

if (head == NULL)
{head = newNode;

Else

Node*temp=head;

While(temp->link!=NULL)

Temp=temp->link;

Temp->link=newNode;

Count++;}

Void display()

Node *current = head;

While (current!=NULL)

{
Cout<<current->info<<”\t”;

Current=current ->link;

Cout<<endl;

Cout<<”Value of count = “<<count<<endl;

Int main()

insertBeg(2);

insertend (21);

insertmiddle(3);

display();

return 0;}

Out Put
Lab 8: Deletion from Linked List
Objectives

To learn about linked list operations including deletion from beginning, middle, end and
display.

Linked List

• Linked List is a linear data structure which is made up of nodes connected by pointers.

• Dynamic Data Structure

• Each node has two parts:

Data: To store information (data)

Link: To store address of next node

Lab Task

#include<iostream>

Using namespace std;

Struct node

Int info;
Node* link;};

Node* head = NULL;

Int count = 0;

Void insertBeg(int data) {

Node* newNode = new node;

newNode->info = data;

newNode->link = head;

head= newNode;

count++;

Void deleteBeg() {

If(head == NULL)

Cout<<”Empty List”;

Else{

Node* ptr = head;


Head=head -> link;

Delete ptr;

Count--;}}

Void deleteMid(){

Node *prev, *ptr;

Int mid = count/2;

Int c = 0;

If(head == NULL)

Cout<<”Empty List”;

Else

If (head-> link == NULL){

Ptr = head;

Head = NULL;

Delete ptr;

Count--;
}

Else {

Ptr = head;

While (c != mid){

C++;

Prev = ptr;

Ptr= ptr -> link;}

Prev -> link=ptr-> link;

Delete ptr;

Count--;}}

Void deleteEnd(){

Node* ptr, *prev;

If(head == NULL)

Cout<<”Empty List”;
Else

If (head-> link == NULL)

Ptr = head;

Head = NULL;

Delete ptr;

Count--;

}else{

Ptr = head;

While (ptr-> link != NULL)

Prev = ptr;

Ptr =ptr -> link;

}
Prev -> link= NULL;

Delete ptr;

Count--;}

Void display()

Node *current = head;

While(current!=NULL)

Cout<<current->info<<”\t”;

Current=current->link;

Cout<<endl;

Cout<<”Value of count = “<<count<<endl;

}
Int main()

insertBeg(92);

insertBeg(29);

insertBeg (12);

insertBeg(34);

insertBeg(21);

deleteBeg();

deleteMid();

deleteEnd();

display();

return 0;

}
Out Put
Lab 9: Linked List based Stack and Queue

Objectives

To learn about linked list based stack and queue implementation.

Stack and Queue Linked List Based Implementation

• Stack -> Push -> Insert at beginning in Singly Linked List

• Stack -> Pop -> Delete from beginning in Singly Linked List

• Queue -> Enqueue -> Insert at end in Singly Linked List

• Queue -> Dequeue -> Delete from Beginning in Singly Linked List
• Check Empty list using the condition head == Null before deletion from stack and queue.

Lab Task

#include <iostream>

Using namespace std;

Struct node

Int info;

Node*link;

};

Node* head = NULL;

Int count = 0;

Void push(int data) {

Node* newNode = new node;

newNode->info = data;

newNode->link = head;
head = newNode;

count++;}

void pop() {

if(head == NULL)

cout<<”Empty List”;

else{

node* ptr = head;

head = head -> link;

delete ptr;

count--;}

Void display()

Node* current = head;

While(current !=NULL)
{ cout<<current->info<<”\t”;

Current=current->link;

Cout<<endl;

Int main(){

Push(92);

Push(29);

Pop();

Push(34);

Display();

Return 0;}
Out Put

Lab Task

#include <iostream>

Using namespace std;

Struct node{

Int info;

Node* link;};

Node* head = NULL;

Int count = 0;

Void Enqueue(int data){

Node* newNode= new node;

newNode->info = data;

newNode->link = NULL;
if (head == NULL)

{head= newNode;}

Else

Node* temp = head;

While (temp->link != NULL)

Temp=temp->link;

Temp->link = newNode;}

Count++;

Void Dequeue() {

If(head == NULL)

Cout<<”Empty List”;

Else{

Node* ptr =head;


Head= head -> link;

Delete ptr;

Count--;}

Void display()

Node *current = head;

While(current!=NULL)

Cout<<current->info<<”\t”;

Current=current->link;

Cout<<endl;

Int main(){
Enqueue (92);

Enqueue (29);

Dequeue();

Enqueue (34);

Display();

Return 0;}

Out Put

Lab 10: Doubly Linked List Insertion and Deletion

Objectives

To learn about Doubly Linked List Insertion and Deletion.

Doubly Linked List


• A doubly linked list is collection of nodes.

• Each node here consists of a data part and two pointers.

• One pointer points to the previous node while the second pointer points to the next node.

• The previous pointer of the head is set to NULL as this is the first node.

• The next pointer of the tail node is set to NULL as this is the last node.

• As the doubly linked list contains two pointers i.e. previous and next, we can traverse it into
the directions forward and backward

Lab Task

#include <iostream>

Using namespace std;

Struct node

Int info;

Node* prev;

Node* next;

};
Node* head = NULL;

Void insert (int data)

Node* newNode= new node;

newNode->info= data;

newNode->next = head;

newNode->prev = NULL;

if (head != NULL)

head->prev= newNode;

head= newNode;

Void delete_node()

Node *temp = head;

Head = head->next;
Delete temp;

Head->prev = NULL;

Void display()

Node *current = head;

While(current!=NULL)

Cout<<current->info<<”\t”;

Current=current->next;

Cout<<endl;

Int main(){

Insert(2);
Insert(6);

Insert(10);

Display();

Delete_node();

Display();

Return 0;

Out Put

LAB 11: Reverse using Linked List


Objectives

To learn about reverse display using linked list.

Doubly Linked List

• A doubly linked list is collection of nodes.

• Each node here consists of a data part and two pointers.

• One pointer points to the previous node while the second pointer points to the next node.

Lab Task

#include <iostream>

Using namespace std;

Struct node

Int info;

Node* prev;

Node* next;
};

Node* head = NULL;

Void insert (int data)

Node* newNode=new node;

newNode->info = data;

newNode->next = head;

newNode->prev = NULL;

if (head != NULL)

head->prev = newNode;

head= newNode;

Void reverseDisplay()

Node *temp = head;


If (temp == NULL)

Return;

While(temp->next!=NULL)

Temp=temp->next;

} while(temp!=NULL)

{ cout<<temp->info<<”\t”;

Temp=temp->prev;

Cout<<endl;

Int main()

Insert(2);

Insert(6);
Insert(10);

reverseDisplay();

return 0;

Out Put
LAB 12: Sorting using Divide and Conquer Approach

Objectives

To learn about divide and conquer algorithms implementation (Merge Sort, Quick Sort)

Merge Sort

The Merge Sort algorithm is a sorting algorithm that is considered as an example of the
divide and conquer strategy. So, in this algorithm, the array is initially divided into two equal
halves and then they are combined in a sorted manner. We can think of it as a recursive
algorithm that continuously splits the array in half until it cannot be further divided. This
means that if the array becomes empty or has only one element left, the dividing will stop, i.e.
it is the base case to stop the recursion. If the array has multiple elements, we split the array
into halves and recursively invoke the merge sort on each of the halves. Finally, when both
the halves are sorted, the merge operation is applied. Merge operation is the process of taking
two smaller sorted arrays and combining them to eventually make a larger one.
General Algorithm

If the list is of a size greater than 1 {

a. Divide the list into two sublists.

b. Merge sort the first sublist.

c. Merge sort the second sublist.

d. Merge the first sublist and the second sublist. }

Quick Sort

Quick Sort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the
given array around the picked pivot. There are many different versions of quick Sort that pick
pivot in different ways.

• Always pick first element as pivot.

• Always pick last element as pivot (implemented below)

• Pick a random element as pivot.

• Pick median as pivot.


The key process in quickSort is partition(). Target of partitions is, given an array and an
element x of array as pivot, put x at its correct position in sorted array and put all smaller
elements (smaller than x) before x, and put all greater elements (greater than x) after x. All
this should be done in linear time.

General Algorithm

If (the list size is greater than 1) {

a. Partition the list into two sub lists, say lower Sub list and upper Sub list.

b. Quick sort lower Sub list.

c. Quick sort upper Sub list.

d. Combine the sorted lower Sub list and sorted upper Sub list.

You might also like