0% found this document useful (0 votes)
96 views9 pages

Merge Sort Based On Link List

The document contains code implementations for various sorting algorithms like merge sort, heap sort, quick sort, insertion sort, bubble sort and selection sort on both linked lists and arrays. It also includes implementations of tree traversal algorithms like finding ancestors of a node in a tree, mirroring a tree. Other data structures concepts covered are function pointers, dynamic memory allocation using new, using stacks and queues in C++.

Uploaded by

taluk2013
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)
96 views9 pages

Merge Sort Based On Link List

The document contains code implementations for various sorting algorithms like merge sort, heap sort, quick sort, insertion sort, bubble sort and selection sort on both linked lists and arrays. It also includes implementations of tree traversal algorithms like finding ancestors of a node in a tree, mirroring a tree. Other data structures concepts covered are function pointers, dynamic memory allocation using new, using stacks and queues in C++.

Uploaded by

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

/* Merge Sort based on Link List */

# include <iostream>
struct node{
int data;
struct node *next;
};
void insert(struct node **head, int data){
struct node *newNode = new(struct node);
newNode->data = data;
newNode->next = (*head);
(*head) = newNode;
}
void display(struct node *head){
struct node *temp = head;
while(temp->next != nullptr){
std::cout<< temp->data <<" ";
temp = temp->next;
}
}
void splitInTwo(struct node *head, struct node **fRef, struct node **sRef){
struct node *slow, *fast;
if(head == nullptr or head->next == nullptr){
*fRef = head;
*sRef = nullptr;
}else{
slow = fast = head;
while( fast->next != nullptr and fast->next->next != nullptr){
slow = slow->next;
fast = fast->next->next;
}

*fRef = head;
*sRef = slow->next;
slow->next = nullptr;

}
struct node *sortedMerge(struct node *fRef, struct node *sRef){
struct node *result = nullptr;
if(fRef == nullptr)
return sRef;
else if(sRef == nullptr)
return fRef;
if(fRef->data <= sRef->data){
result = fRef;
result->next = sortedMerge(fRef->next, sRef);
}else{
result = sRef;
result->next = sortedMerge(fRef,sRef->next);
}
return result;
}
void mergeSort(struct node **headRef){
struct node *a, *b;
struct node *head = *headRef;
if(head == nullptr or head->next == nullptr)
return;
splitInTwo(head,&a,&b);
mergeSort(&a);
mergeSort(&b);
}

*headRef = sortedMerge(a,b);

int main(int argc, char *argv[]){


struct node *head = nullptr;
insert(&head,10);
insert(&head, 2);
insert(&head,7);
insert(&head, 15);
insert(&head,11);
insert(&head, 9);
insert(&head,1);
insert(&head, 4);
insert(&head,31);
insert(&head, 29);
insert(&head,121);

insert(&head, 42);
//display(head);
mergeSort(&head);
display(head);
return 0;
}

/* Heap sort based on Arrays */


# include<iostream>
int parent(int loc){
return loc/2;
}
int left(int loc){
return 2* loc;
}
int right(int loc){
return 2*loc + 1;
}
void maxHeapify(int *A, int size, int loc){
int leftLoc, rightLoc, largest;
int tempVal;
leftLoc = left(loc);
rightLoc = right(loc);
if(leftLoc <= size and A[leftLoc-1] > A[loc-1])
largest = leftLoc;
else
largest = loc;
if(rightLoc <= size and A[rightLoc-1] > A[largest-1])
largest = rightLoc;

if(largest != loc){
tempVal = A[loc-1];
A[loc-1] = A[largest-1];
A[largest-1] = tempVal;
maxHeapify(A, size, largest);
}

void buildMaxHeap(int *A, int size){


for(int i = size/2; i >0 ; --i){
maxHeapify(A, size, i);
}
}
void heapSort(int *A, int size){
int temp;
buildMaxHeap(A,size);
for(int i = size; i >= 1; --i){
std::cout << A[0] << " ";
A[0] = A[i-1];
size = size - 1;
maxHeapify(A, size, 1);
}
}
void displayArray(int * A, int size){
for(int i = 0; i< size; i++){
std::cout << A[i] <<" ";
}
}
int main(int argc, char *argv[]){
int size = 10;
int array[10] = {4,1,3,2,16,9,10,14,8,7};
heapSort(array, size);
return 0;
}

Algorithm

Worst Case
running time

Average Case
Expected Running Time

insertion Sort
Merge Sort
HeapSort
QuickSort
Counting Sort
Radix Sort
Bucket Sort

O(n^2)
O(nlg n)
O(nlg n)
O(n^2)
O(k+n)
O(d(n+k))
O(n^2)

O(n^2)
O(nlg n)
O(nlg n) (expected)
O(k+n)
O(d(n+k))
O(n)
(average case)

/* Insertion Sort Using Arrays*/


#include<iostream>
void insertionSort(int *array, int len){
int j, temp;
for(int i =1; i<len; ++i){
j = i;
while( j >0 && array[j] < array[j-1]){
temp = array[j];
array[j] = array[j-1];
array[j-1] = temp;
j--;
}
}
}
int main(int argc, char *argv[]){
int array[10] = {9,3,5,1,4,3,2,12,7,10}
insertionSort(array,10);
return 1;
}

/* Bubble Sort based on Arrays*/


void bubbleSort(int *array, int len){
for(int i = 0; i <len; ++i){
for(int j = 0; j <len-1;++j){
if(array[j]>array[j+1]){
int temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
}
}
}
}
/* Selection Sort based on Arrays*/
void selectionSort(int *array, int len){
int minVal, minSelect, temp;
for(int i = 0; i <len; ++i){
minVal = INT_MAX;
for(int j= i; j<len; ++j){
if(array[j]< minVal){
minVal = array[j];
minSelect = j;
}
}
if(array[i] > array[minSelect]){
//swap
temp = array[i];
array[i] = array[minSelect];
array[minSelect] = temp;
}
}
}

/* Quick Sort on Link List */


# include <iostream>
struct node{
int data;
struct node *next;
};
void insert(struct node **head, int data){
struct node *newNode = new(struct node);
newNode->data = data;
newNode->next = (*head);
(*head) = newNode;
}
void display(struct node* head){
struct node *temp = head;
while(temp->next != nullptr){
std::cout << temp->data << " ";
temp = temp->next;
}
}
/* returns the last node of the list */
struct node *getTail(struct node *curr){
while(curr != nullptr and curr->next != nullptr){
curr = curr->next;
}
return curr;
}
struct node *partition(struct node *head, struct node *end, struct node **newHead, struct node **newEnd){
struct node *pivot = end;
struct node *prev = nullptr, *cur = head, *tail = pivot;
// During partition, both the head and end of the list might change
// which is updated in the newHead and newEnd variables
while(cur != pivot){
// First node that has a value less than the pivot - becomes
// the new head
if(cur->data < pivot->data){
if((*newHead) == nullptr)
(*newHead) = cur;
prev = cur;
cur = cur->next;
}else{ // If cur node is greater than pivot
// Move cur node to next of tail, and change tail
if(prev)
prev->next = cur->next;
struct node *temp = cur->next;
cur->next = nullptr;
tail->next = cur;
tail = cur;
cur= temp;
}
}
// If the pivot data is the smallest element in the current list,
// pivot becomes the head
if((*newHead) == nullptr)
(*newHead) = pivot;
// Update newEnd to the current last node
(*newEnd) = tail;

// Return the pivot node


return pivot;

struct node *quickSortRecur(struct node *head, struct node *end){


if (!head or head == end){
return head;
}
node *newHead = nullptr, *newEnd = nullptr;
struct node *pivot = partition(head, end, &newHead, &newEnd);
if(newHead != pivot){
struct node *temp = newHead;
while(temp->next != pivot){
temp = temp->next;

}
temp->next = nullptr;
newHead = quickSortRecur(newHead, temp);
temp = getTail(newHead);
temp->next = pivot;
}
pivot->next = quickSortRecur(pivot->next, newEnd);
return newHead;
}
/* main quick-sort routine*/
void quickSort(struct node **headRef){
(*headRef) = quickSortRecur(*headRef, getTail(*headRef));
}
int main(int argc, char * argv[]){
struct node *head = nullptr;
insert(&head,10);
insert(&head, 2);
insert(&head,7);
insert(&head, 15);
insert(&head,11);
insert(&head, 9);
insert(&head,1);
insert(&head, 4);
insert(&head,31);
insert(&head, 29);
insert(&head,121);
insert(&head, 42);
quickSort(&head);

display(head);
return 0;

/* Function to reverse the linked list */


static void reverse(struct node** head_ref)
{
struct node* prev
= NULL;
struct node* current = *head_ref;
struct node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
/* Function to reverse the linked list

with Single Local Function Variable */

struct list {
struct list *next;
};
struct list *reverse(struct list *cur, struct list *prev) {
struct list *next = cur->next;
cur->next = prev;
if(next == NULL) return cur;
return reverse(next, cur);
}
reverse(head, NULL);
/* Find the ancestors of a node in Tree */
bool printAncestors(struct node *root, int target)
{
/* base cases */
if (root == NULL)
return false;
if (root->data == target)
return true;
/* If target is present in either left or right subtree of this node,

then print this node */


if ( printAncestors(root->left, target) ||
printAncestors(root->right, target) )
{
cout << root->data << " ";
return true;
}

/* Else return false */


return false;

/* Array based Quick Sort */


# include<iostream>
void swap(int &val1, int &val2){
int temp;
temp = val1;
val1 = val2;
val2 = temp;
}
int partition(int *A, int loc, int size){
int x, i;
x = A[size];
i = loc - 1;
for(int j = loc; j<= size-1; j++){
if (A[j] <= x){
i++;
swap(A[i], A[j]);
}
}
swap(A[i+1], A[size]);
return i+1;
}

// selecting pivot

int quicksort(int *A, int loc, int size){


int pLoc;
if(loc<size){
pLoc = partition(A,loc,size);
quicksort(A, loc, pLoc-1);
quicksort(A, pLoc + 1, size);
}
return 0;
}
void displayArray(int *A, int size){
for(int i = 0; i< size; i++){
std::cout << A[i] <<" ";
}
}
int main(int argc, char *argv[]){
int size = 10;
int array[10] = {4,1,3,2,16,9,10,14,8,7};
quicksort(array,0,size-1);
displayArray(array, size);
return 0;
}
/* Mirror of a tree */
void mirror (struct node *root){
if(root == nullptr){
return;
}else{
struct node *temp;
mirror(root->left);
mirror(root->right);
/* swap the pointers in the node */
temp = root->left;
root->left = root->right;
root->right = temp;
}

/* Ceveats !*/
i++ makes a copy, increases _i and returns the copy (old value)
++i increases _i, and returns _i.

/* Function Pointer */
#include <iostream>
using namespace std;
int addition (int a, int b){
return (a+b);
}
int subtraction (int a, int b){
return (a-b);
}
int operation (int x, int y, int (*functocall)(int,int)){
int g;
g = (*functocall)(x,y);
return (g);
}
int main (){
int m,n;
int (*minus)(int,int) = subtraction;
m = operation (7, 5, addition);
n = operation (20, m, minus);
cout <<n;
return 0;
}

/* Allocating in dynamic memory */


pointer = new type [number_of_elements]

/* Using a simple stack */

/* Using a simple queue */

# include<iostream>
# include<stack>

# include<iostream>
# include<queue>

void inStack(std::stack<int> *inStack, int element){


inStack->push(element);
}

void inQueue(std::queue<int> *inQueue, int element){


inQueue->push(element);
}

void delStack(std::stack<int> *popStack){


popStack->pop();
}

void delQueue(std::queue<int> *popQueue){


popQueue->pop();
}

void showfrontStack(std::stack<int> *showStack){


std::cout << showStack->top();
}

void showfrontQueue(std::queue<int> *showQueue){


std::cout << showQueue->front();
}

bool isStackEmpty(std::stack<int> *checkStack){


if(checkStack->empty())
std::cout<< true;
}

bool isQueueEmpty(std::queue<int> *checkQueue){


if(checkQueue->empty())
std::cout<< true;
}

int main(int argc, char *argv[]){

int main(int argc, char *argv[]){

std::stack <int> myStack;


inStack(&myStack,17);
inStack(&myStack,65);
showfrontStack(&myStack);
delStack(&myStack);
showfrontStack(&myStack);
delStack(&myStack);
isStackEmpty(&myStack);
return 0;

std::queue <int> myqueue;


inQueue(&myqueue,17);
inQueue(&myqueue,65);
showfrontQueue(&myqueue);
delQueue(&myqueue);
showfrontQueue(&myqueue);
delQueue(&myqueue);
isQueueEmpty(&myqueue)
return 0;

/* Find the diameter of a tree */


int findDiam (struct node *root, int *height){
int lh = 0, rh = 0;
int ldiam = 0 , rdiam = 0;
if(root == nullptr){
*height = 0;
return 0;
}
ldiam = findDiam(root->left, &lh);
rdiam = findDiam(root->right, &rh);
*height = maximum(lh,rh) + 1;
return maximum((lh+rh+1), maximum(ldiam,rdiam));

/*Level Order Traversal Using Recursion */


int height(struct node *root){
if (node == nullptr)
return 0;
}else{
/*compute the height of each subtree */
int lh = height(root->left);
int rh = height(root->right);
/*use the larger one */
if(lheight>rheight){
return (lheight +1);
}else{
return (rheight +1);
}
}
void printgivenLevel(struct node *root, int level){
if (root == nullptr)
return;
if(level == 1)
std::cout << root->data;
elseif(level >1){
printgivenLevel(root->left,level-1);
printgivenLevel(root->right,level-1);
}
}
void printLevelOrder(struct node *node){
int h = height(root);
for(int I = 0; i<=h, i++){
printgivenLevel(root,i);
}
}
/* Bit Manipulation */
Setting a bit
Clearing a bit
Toggling a bit

:
:
:

number |= 1 << x
number &= ~(1<<x)
number ^= (1<<x)

bit Variable:
struct bits{
unsigned int a:1;
unsigned int b:1;
};
struct bits mybits;
/* Atoi implementation */
int atoi(const std::string &str){
int num = 0;
for(std::string::iterator it = str.begin(); it != str.end(); ++it ){
if( *it < '0' || *it > '9'){
return num;
}
num = * 10;
num += *it - '0';
}
return num;
}

/* breadth first search */


void BFStraverse(std::unordered_map<std::string, node*> &graph, std::string sstart){
std::queue<node *> myqueue;
std::forward_list<node *> rlist;
std::unordered_map<std::string, node*>::const_iterator t1 = graph.find(sstart);
node *start = t1->second;
// start node
myqueue.push(start);
while(!myqueue.empty()){
start = myqueue.front();
start->updateNodeAsVisited();
std::cout<< start->shownodeName()<< " ";
// bfs traverse
rlist = start->getnodeLink();
for(auto it =rlist.begin(); it !=rlist.end(); ++it){
if(!(*it)->nodeVisitStatus())
myqueue.push(*it);
}
myqueue.pop();
}
}
/* depth first search */
void DFStraverse(std::unordered_map<std::string, node*> &graph, std::string sstart){
std::stack<node*> mystack;
std::forward_list<node *> rlist;
bool isAllAdjNodeVisited = 1;
std::unordered_map<std::string, node*>::const_iterator t1 = graph.find(sstart);
node *start = t1->second;
// start node
mystack.push(start);
while(!mystack.empty()){
start = mystack.top();
if(!start->nodeVisitStatus()){
start->updateNodeAsVisited();
std::cout<< start->shownodeName()<< " ";
// dfs traverse
}
rlist = start->getnodeLink();
for(auto it =rlist.begin(); it !=rlist.end(); ++it){
if(!(*it)->nodeVisitStatus()){
mystack.push(*it);
isAllAdjNodeVisited = 0;
break;
}
}
if(isAllAdjNodeVisited){
mystack.pop();
}
isAllAdjNodeVisited = 1;
}
}

You might also like