Showing posts with label Cpp Programming. Show all posts
Showing posts with label Cpp Programming. Show all posts

Monday, 29 February 2016

Data Structures - Infix to Postfix Conversion - Cpp


In this post we convert an infix expression to postfix expression using stack data structure .

Generally an infix expression is a normal expression where operators are present in between the operands ex : A + B * C and  its postfix  notation is represented as ABC*+


An infix expression is converted into its postfix notation as follows :

  • Create an empty Stack for pushing and poping operators and a string for storing result
  • First scan the infix exppression from left to right if there is no exponential operator , if there is an exponential operator scan the infix expression from right to left.
  • If an operand is encountered add it to the result string
  • If a left parenthesis is encountered push it to the stack
  • If a right parenthesis is encountered pop the stack until its corresponding left parenthesis is removed and append each operator to the result string  
  • If an operator is encountered push it to the stack if the encountered operator is of lower precedence that the stack top element and pop all elements with higher or equal precedence and add to result string.
  • Check if there are any elements in the stack and pop them out and add to the result string.


Download code

PROGRAM :

    #include<iostream>
    #include<stack>
    #include<string>

    using namespace std;
    string InfixToPostfix(string expression);
    int HasHigherPrecedence(char operator1, char operator2);
    bool IsOperator(char C);
    bool IsOperand(char C);

    int main()
    {
        string expression;
        cout<<"Enter Infix Expression: \t";
        getline(cin,expression);
        string postfix = InfixToPostfix(expression);
        cout<<"Postfix expression = \t"<<postfix<<"\n";
        return 0;
    }
    string InfixToPostfix(string expression)
    {

        stack<char> S;
        string postfix = "";
        for(int i = 0; i< expression.length(); i++)
        {
        if(expression[i] == ' ' || expression[i] == ',')
            continue;
        else if(IsOperator(expression[i]))
        {
            while(!S.empty() && S.top() != '(' && HasHigherPrecedence(S.top(),expression[i]))
            {
                postfix+= S.top();
                S.pop();
            }
            S.push(expression[i]);
        }
        else if(IsOperand(expression[i]))
        {
            postfix +=expression[i];
        }

        else if (expression[i] == '(')
        {
            S.push(expression[i]);
        }

        else if(expression[i] == ')')
        {
            while(!S.empty() && S.top() !=  '(')
            {
                postfix += S.top();
                S.pop();
            }
            S.pop();
        }
        }

        while(!S.empty())
        {
        postfix += S.top();
        S.pop();
        }

        return postfix;
    }
    bool IsOperand(char C)
    {
        if(C >= '0' && C <= '9') return true;
        if(C >= 'a' && C <= 'z') return true;
        if(C >= 'A' && C <= 'Z') return true;
        return false;
    }
    bool IsOperator(char C)
    {
        if(C == '+' || C == '-' || C == '*' || C == '/' || C== '^')
        return true;
        return false;
    }
    int IsRightAssociative(char op)
    {
        if(op == '^')
        return true;
        return false;
    }
    bool IsLeftParenthesis(char ch)
    {
        if (ch == '(')
        return true;
        return false;
    }
    bool IsRightParenthesis(char ch)
    {
        if (ch == ')')
        return true;
        return false;
    }
    int GetOperatorWeight(char op)
    {
        int weight = -1;
        switch(op)
        {
        case '+':
        case '-':
        weight = 1;
        break;
        case '*':
        case '/':
        weight = 2;
        break;
        case '^':
        weight = 3;
        break;
        }
        return weight;
    }
    int HasHigherPrecedence(char op1, char op2)
    {
        int op1Weight = GetOperatorWeight(op1);
        int op2Weight = GetOperatorWeight(op2);
        if(op1Weight == op2Weight)
        {
        if(IsRightAssociative(op1))
            return false;
        else
            return true;
        }
        return op1Weight > op2Weight ?  true: false;
    }
Download code

OUTPUT :

Cpp - Data Structures - Infix to Postfix 

Cpp - Data Structures - Infix to Postfix 

Cpp - Data Structures - Infix to Postfix 

Tuesday, 23 February 2016

Data Structures - Cpp Program to implement Linked List Operations - Insert , Delete , Update , Display

Linked List is another data structure consisting of group of nodes which together represent a sequence. Each node has two parts one for the value and other for link to the next node.
Linked lists allows dynamic memory allocation.

Singly-linked-list.svg
A singly linked list whose nodes contain two fields: an integer value and a link to the next node


Some of the operations in a linked list are :

  • Insertion into the list
  • Deletion from the list
  • Updation of the value
  • Display the list





Download code

PROGRAM :

        #include<iostream>
 #include<cstdio>
 #include<cstdlib>

 using namespace std;


 struct node
 {
     int value;
     struct node *next;
 }*start;

 typedef struct node snode;
 snode *newnode, *ptr, *prev, *temp;
 snode *first = NULL, *last = NULL;

 class LinkedList
 {
 public:
     node* create_node(int);
     void insertNodeFirst();
     void insertNodeLast();
     void insertNodePosition();
     void deleteNode();
     void updateNode();
     void displayList();
     LinkedList()
     {
  start = NULL;
     }
 };

 int main()
 {
     int ch;
     char ans = 'Y';
     LinkedList ll;
     while (ans == 'Y'||ans == 'y')
     {
  cout << "\n1.Insert node at first";
  cout << "\n2.Insert node at last";
  cout << "\n3.Insert node at position";
  cout << "\n4.Delete Node from any Position";
  cout << "\n5.Update Node Value";
  cout << "\n6.Display List";
  cout << "\n7.Exit\n";
  cout << "\nEnter your choice: \t";
  cin >> ch;

  switch (ch)
  {
  case 1:
      ll.insertNodeFirst();
      break;
  case 2:
      ll.insertNodeLast();
      break;
  case 3:
      ll.insertNodePosition();
      break;
  case 4:
      ll.deleteNode();
      break;
  case 5:
      ll.updateNode();
      break;
  case 6:
      ll.displayList();
      break;
  case 7:
      return 0;
      break;
  default:
      cout << "\nInvalid Choice\n";
      break;
  }
  cout << "\nDo you want to continue ? (Y/N) \t";
  cin >> ans;
     }
     return 0;
 }
 snode* createNode(int val)
 {
     newnode = (snode *)malloc(sizeof(snode));
     if (newnode == NULL)
     {
  cout << "\nMemory was not allocated";
  return 0;
     }
     else
     {
  newnode->value = val;
  newnode->next = NULL;
  return newnode;
     }
 }
 void LinkedList::insertNodeFirst()
 {
     int val;
     cout << "\nEnter the value for the node: \t";
     cin >> val;
     newnode = createNode(val);
     if (first == last && first == NULL)
     {
  first = last = newnode;
  first->next = NULL;
  last->next = NULL;
     }
     else
     {
  temp = first;
  first = newnode;
  first->next = temp;
     }
     cout << "\nInserted Successfully";
 }
 void LinkedList::insertNodeLast()
 {
     int val;

     cout << "\nEnter the value for the Node: \t";
     cin >> val;
     newnode = createNode(val);
     if (first == last && last == NULL)
     {
  first = last = newnode;
  first->next = NULL;
  last->next = NULL;
     }
     else
     {
  last->next = newnode;
  last = newnode;
  last->next = NULL;
     }
     cout << "\nInserted Successfully";
 }
 void LinkedList::insertNodePosition()
 {
     int pos, val, count = 0, i;
     cout << "\nEnter the value for the Node: \t";
     cin >> val;
     newnode = createNode(val);
     cout << "\nEnter the position: \t";
     cin >> pos;
     ptr = first;
     while (ptr != NULL)
     {
  ptr = ptr->next;
  count++;
     }
     if (pos == 1)
     {
  if (first == last && first == NULL)
  {
      first = last = newnode;
      first->next = NULL;
      last->next = NULL;
  }
  else
  {
      temp = first;
      first = newnode;
      first->next = temp;
  }
  cout << "\nInserted Successfully";
     }
     else if (pos>1 && pos<=count)
     {
  ptr = first;
  for (i = 1; i < pos; i++)
  {
      prev = ptr;
      ptr = ptr->next;
  }
  prev->next = newnode;
  newnode->next = ptr;
  cout << "\nInserted Successfully";
     }
     else
     {
  cout << "Position is out of range";
     }
 }
 void LinkedList::deleteNode()
 {
     int pos, count = 0, i;

     if (first == NULL)
     {
  cout << "No nodes in the list to delete\n";
     }
     else
     {
  cout << "\nEnter the position of value to be deleted: \t";
  cin >> pos;
  ptr = first;
  if (pos == 1)
  {
      first = ptr->next;
      cout << "\nElement deleted successfully";
  }
  else
  {
      while (ptr != NULL)
      {
          ptr = ptr->next;
          count = count + 1;
      }
      if (pos > 0 && pos <= count)
      {
          ptr = first;
          for (i = 1; i < pos; i++)
          {
              prev = ptr;
              ptr = ptr->next;
          }
          prev->next = ptr->next;
      }
      else
      {
          cout << "Position is out of range";
      }
      free(ptr);
      cout << "\nElement deleted successfully";
  }
     }
 }
 void LinkedList::updateNode()
 {
     int oldval, newval, flag = 0;

     if (first == NULL)
     {
  cout << "No nodes in the list to update\n";
     }
     else
     {
  cout << "\nEnter the value to be updated: \t";
  cin >> oldval;
  cout << "\nEnter the new value: \t";
  cin >> newval;
  for (ptr = first; ptr != NULL; ptr = ptr->next)
  {
      if (ptr->value == oldval)
      {
          ptr->value = newval;
          flag = 1;
          break;
      }
  }
  if (flag == 1)
  {
      cout << "\nUpdated Successfully";
  }
  else
  {
      cout << "\nValue not found in List";
  }
     }
 }
 void LinkedList::displayList()
 {
     if (first == NULL)
     {
  cout << "No nodes in the list to display\n";
     }
     else
     {
  for (ptr = first; ptr != NULL; ptr = ptr->next)
  {
      cout <<  ptr->value << "\t";
  }
     }
 }
 
Download code

OUTPUT :

Cpp - Linked List Operations - Insertion at front

Cpp - Linked List Operations - Insertion at last and  any position

Cpp - Linked List Operations -  Deletion of node

Cpp - Linked List Operations - Updation of value

Cpp - Linked List Operations - Display List
Download code

Tuesday, 16 February 2016

Data Structures - Cpp Program to implement queue operations using an array

Queue is a data structure  , similar to Stack , but here in queue we have openings at both the ends , one for insertion and other for deletion.


Some of the common operations of queue are :

  • Adding an item to queue(enqueue)
  • Removing an item from a queue(dequeue)
  • Overflow Condition(Queue full)
  • Underflow Condition(Queue empty)
  • Getting the front element(peek)



Overflow situation occur when the queue is full and then we are trying to  insert/add another item to the queue .

Underflow situation occur when the queue is empty and the we are trying to remove/delete an item from the queue.

The principle of  queue is First In First Out (FIFO).


Download code

PROGRAM :

#include <iostream>

using namespace std;

int main()
{
    int rear = -1,front = -1,item,MAX ,choice ,i;
    cout << "Enter Size of Queue : \t ";
    cin >> MAX;
    int QueueArray[MAX];
    while (1)
    {
        cout << "\nQueue Operations  :";
        cout << "\n1. Insert/Add";
        cout << "\n2. Remove/Delete";
        cout << "\n3. Peek/Front item";
        cout << "\n4. Display Queue";
        cout << "\n5. Exit";
        cout << "\nEnter your choice :\t";
        cin >> choice;
        switch (choice)
        {
        case 1:
            if (rear == MAX - 1)
            {
                cout << "Queue Overflow \n";
            }
            else
            {
                if (front == -1)
                {
                    front = 0;
                }
                cout << "Inset the element in queue : \t";
                cin >> item;
                rear = rear + 1;
                QueueArray[rear] = item;
            }

            break;
        case 2:

            if (front == -1 || front > rear)
            {
                cout << "Queue Underflow \n";
                break;
            }
            else
            {
                cout << "Element deleted from queue is " <<  QueueArray[front] << "\n" ;
                front = front + 1;
            }
            break;
        case 3:
            if (front == -1 || front > rear)
            {
                cout << "Queue Underflow \n";
                break;
            }
            else
            {
                cout << "The front element is :" << QueueArray[front] << "\t" ;
            }
            break;
        case 4:
            if (front == -1 || front > rear)
            {
                cout << "Queue Underflow \n";
                break;
            }
            else
            {
                cout << "The current elements in queue are :";
                for (i = front; i <= rear; i++)
                {
                    cout << QueueArray[i];
                }
            }
            break;
        case 5:
            return 0;
            break;
        default:
            cout << "Wrong Entry \n ";
            break;
        }

    }
    return 0;
}
Download code

OUTPUT : 

Cpp - Queue Operations
Cpp- Queue Overflow
   
Cpp - Queue Underflow
Download code

Friday, 5 February 2016

CPU Scheduling Algorithm - Round Robin(Cpp)


This is a Cpp program which implements one of the CPU Scheduling algorithm called Round Robin(RR).

Round robin algorithm is mainly used in time sharing systems , it is also similar to First Come First Served(FCFS) algorithm but FCFS does not have that time slicing switch.

All the jobs gets executed in this scheduling algorithm , so the advantage here is , its Starvation free.




Download Code

PROGRAM :

#include <iostream>

using namespace std;

int main()
{
    int bt_c[10],bt[10],i,j,n,m[50],r,q,e=0;
    float f,avg=0;
    cout << "\nEnter how many jobs ?\t";
    cin >> n;
    for(i=1; i<=n; i++)
    {
        cout << "Enter burst time for job %d :\t" << i;
        cin >> bt[i]);
        bt_c[i]=bt[i]; //stores job has how much burst  time in array  i
    }
    cout << "\nEnter Quantum (time slice value) :\t";
    cin >> q;
    int max=0;
    max=bt[1];
    for(j=1; j<=n; j++)
        if(max<=bt[j])
            max=bt[j];

    if((max%q)==0)
        r=(max/q);
    else
        r=(max/q)+1;
    for(i=1; i<=r; i++)
    {
        cout << "\n\nRound" << i;
        for(j=1; j<=n; j++)
        {
            if(bt[j]>0)
            {
                bt[j]=bt[j]-q;

                if(bt[j]<=0)
                {
                    bt[j]=0;
                    cout << "\njob %d is completed" << j;
                }
                else
                    cout << "\njob" <<  j << " remaining time is " << bt[j];
            }
        }

    }
    for(i=1; i<=n; i++)
    {
        e=0;
        for(j=1; j<=r; j++)
        {
            if(bt_c[i]!=0)
            {
                if(bt_c[i]>=q)
                {
                    m[i+e]=q;
                    bt_c[i]-=q;
                }
                else
                {
                    m[i+e]=bt_c[i];
                    bt_c[i]=0;
                }
            }
            else
                m[i+e]=0;
            e=e+n;
        }
    }
    for(i=2; i<=n; i++)
        for(j=1; j<=i-1; j++)
            avg=avg+m[j];
    for(i=n+1; i<=r*n; i++)
    {
        if(m[i]!=0)
        {
            for(j=i-(n-1); j<=i-1; j++)
                avg=m[j]+avg;
        }
    }
    f=avg/n;
    cout << "\n\n\nTOTAL WATING TIME:" << avg << "\t";
    cout << "\n\nAVERAGE WAITING TIME:" << f << "\t\n";
    return 0;
}
Download Code

OUTPUT :

Cpp Programming - CPU Scheduling Algorithm - Round Robin

Sunday, 31 January 2016

Cpp Program to find length of a string using strlen function


This is a Cpp Program to find the length of a String.
Here we use string function strlen() to find the length of a string.
All the string functions are present in the header string.h




Download Code

PROGRAM :

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    char name[40];
    cout << "Enter any name(String) : \t";
    cin.get(name , 40);
    cout << "\nThe length of the string you entered is : \t" << strlen(name) << endl;
    return 0;
}

OUTPUT : 

Cpp Program - Length of a string

Getting Started with Strings in Cpp - Reading a string and displaying it

This is a simple Cpp Program to read and display the content of the string.

Download Code

PROGRAM :

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    char name[40];
    cout << "Enter any name(String) : \t";
    cin.get(name , 40);
    cout << "\nThe length of the string you entered is : \t" << strlen(name) << endl;
    return 0;
}

OUTPUT :

Cpp Program - Reading and displaying a string

Cpp Program to print triangle with numbers

This is a simple Cpp Program which prints out a triangle with respect to the input given , here the obtained triangle is filled with numbers.

Triangle pattern with numbers

Download Code

PROGRAM :

#include <iostream>

using namespace std;

int main()
{
    int i, j, n,k;
    cout << "Enter number of lines[height of triangle] : \t";
    cin >> n;
    for(i=1; i<=n; i++)
    {
        for(j=i; j<n; j++)
        {
            cout << " ";
        }
        for(k=1; k<(i*2); k++)
        {
            cout << k;
        }
        cout << "\n";
    }
    return 0;
}

OUTPUT :

Cpp Program - Triangle with numbers

Cpp Program to print a triangle with stars

This is a simple Cpp Program which prints out a triangle with respect to the input given , the obtained triangle is  filled with stars.

Triangle pattern with stars

Download Code

PROGRAM :

#include <iostream>

using namespace std;

int main()
{
    int i, j, n,k;
    cout << "Enter number of lines[height of triangle] : \t";
    cin >> n;
    for(i=1; i<=n; i++)
    {
        for(j=i; j<n; j++)
        {
            cout << " ";
        }
        for(k=1; k<i*2; k++)
        {
            cout << "*";
        }
        cout << "\n";
    }
    return 0;
}


OUTPUT : 

Cpp Program to print a triangle with stars

Saturday, 30 January 2016

Cpp Program to print a Right angled triangle

This is a simple Cpp Program which prints out a Right angled triangle with respect to the input given.

Right angled triangle pattern program
Download Code
PROGRAM :


#include <iostream>

using namespace std;

int main()
{
    int i, j, n,k;
    cout << "Enter number of lines[height of triangle] : \t";
    cin >> n;
    for(i=1; i<=n; i++)
    {
        for(j=i; j<n; j++)
        {
            cout << " ";
        }
        for(k=1; k<(i*2); k++)
        {
            cout << k++;
        }
        cout << "\n";
    }
    return 0;
}


Download Code
OUTPUT :
Cpp Program - Right angled triangle pattern

Cpp Program to print Pascals triangle

This is a Cpp Program which prints pascals triangle based on the input given.

Pascals Triangle


Download Code
PROGRAM : 

#include <iostream>

using namespace std;

int main()
{
     int i,j,x,n,s;
    cout << "Enter number of lines[height of triangle] : \t";
    cin >> n;
    for(i=0; i<=n; i++)
    {
        x=1;
        for(s=1; s<=n-i; s++)
            cout << " ";
        for(j=1; j<=i+1; j++)
        {
            cout << " " << x;
            x=x*(i-j+1)/j;
        }
        cout << "\n";
    }
    return 0;
}

Download Code
OUTPUT : 
Cpp Program to print pascals triangle


Tuesday, 26 January 2016

Cpp Program to print palindrome triangle

This is a Cpp Program which prints thee palindrome triangle based on the input given.

Here , check each row elements , you can see a palindrome sequence.
Palindrome triangle

Download Code

PROGRAM :

#include <iostream>

using namespace std;

int main()
{
    int i,j,n;
    cout << "Enter number of lines[height of triangle] : \t";
    cin >> n;
    for(i=1; i<=n; i++)
    {
        for(j=i; j<n; j++)
            cout << " ";
        for(j=1; j<=i; j++)
            cout << j;
        for(j=i-1; j>=1; j--)
            cout << j;
        cout << "\n";
    }
    return 0;
}

OUTPUT :

Cpp program - Palindrome triangle

Download Code

Cpp Program to print Floyds triangle

This is a Cpp program which prints the Floyd's triangle with respect to the input given.

Floyds triangle


Download Code

PROGRAM :

#include <iostream>

using namespace std;

int main()
{
    int i, j, k = 1,n;
    cout << "Enter the range: ";
    cin >> n;
    cout << "\nFLOYD'S TRIANGLE : \n";
    for (i = 1; i <= n; i++)
    {
        for (j = 1; j <= i; j++, k++)
        {
            cout << "\t" << k;
        }
        cout << "\n" ;
    }
    return 0;
}

OUTPUT :

Cpp Program - Floyds Triangle

Cpp program to print diamond with stars

This is a  Cpp Program which prints out the diamond with stars pattern.

Diamond with stars ( pattern)
Download Code
PROGRAM :

#include <iostream>

using namespace std;

int main()
{
    int i, j, k,n;
    cout << "Enter number of lines[height of diamond] : \t" ;
    cin >> n;
    for(i=1; i<=n; i++)
    {
        for(j=i; j<n; j++)
        {
            cout << " ";
        }
        for(k=1; k<(i*2); k++)
        {
            cout << "*";
        }
        cout << "\n";
    }
    for(i=n-1; i>=1; i--)
    {
        for(j=n; j>i; j--)
        {
            cout << " ";
        }
        for(k=1; k<(i*2); k++)
        {
            cout << "*";
        }
        cout << "\n";
    }

    return 0;
}


OUTPUT :
Cpp Program  - Diamond pattern with stars

Download Code

Sunday, 26 April 2015

Cpp Program for sorting elements using Heap Sort


This is a Cpp Program which sorts all the elements using Heap Sort technique.

Look at the below animation ,

Heapsort-example.gif
"Heapsort-example" by Swfung8 - Own work. Licensed under CC BY-SA 3.0 via Wikimedia Commons.




Download Code
PROGRAM : 
#include <iostream>

using namespace std;

int main()
{
    int heap[10], no, i, j, c, root, temp;

    cout << "How many numbers? \t";
    cin  >> no;
    cout << "\n\n";
    for (i = 0; i < no; i++)
    {
        cout << "Enter number "<< i+1 <<" :\t";
        cin >> heap[i] ;
    }

    for (i = 1; i < no; i++)
    {
        c = i;
        do
        {
            root = (c - 1) / 2;
            if (heap[root] < heap[c])
            {
                temp = heap[root];
                heap[root] = heap[c];
                heap[c] = temp;
            }
            c = root;
        }
        while (c != 0);
    }

    cout << "\n\nThe Heap array  is: \n\n";
    for (i = 0; i < no; i++)
        cout << heap[i] << "\t";
    for (j = no - 1; j >= 0; j--)
    {
        temp = heap[0];
        heap[0] = heap[j];
        heap[j] = temp;
        root = 0;
        do
        {
            c = 2 * root + 1;
            if ((heap[c] < heap[c + 1]) && c < j-1)
                c++;
            if (heap[root]<heap[c] && c<j)
            {
                temp = heap[root];
                heap[root] = heap[c];
                heap[c] = temp;
            }
            root = c;
        }
        while (c < j);
    }
    cout << "\n\nThe sorted array is : \n\n";
    for (i = 0; i < no; i++)
        cout << heap[i] << " \t";
    return 0;
}


Download Code
OUTPUT :
Cpp - Heap Sort

Cpp Program for sorting elements using Quick Sort



This is a Cpp program which sorts all the elements using Quick sort technique.

Select an element and make it as pivot , the arrangement should be such that all the elements less than pivot should on left side of it and all the elements greater than it should be on its right side. Then do the same process for the elements left and right of the pivot . the final result is the sorted array.






See the below fig ,


Quicksort-diagram.svg
"Quicksort-diagram" by Znupi - Own work. Licensed under Public Domain via Wikimedia Commons.



Download Code
PROGRAM : 

#include <iostream>

using namespace std;
void quick_sort(int [],int,int);
int main()
{
    int arr[20],n,i;
    cout << "How many numbers ? \t";
    cin >> n;

    for(i=0 ; i<n ; i++)
    {
        cout << "\nEnter number  " << i+1 << " :\t";
        cin >> arr[i];
    }
    quick_sort(arr,0,n-1);
    cout << "\n\nThe Sorted Array is:\n\n";
    for(i=0 ; i<n ; i++)
    {
        cout << arr[i] << "\t";
    }
    return 0;
}
void quick_sort(int arr[20],int low,int high)
{
    int pivot,j,temp,i;
    if(low<high)
    {
        pivot = low;
        i = low;
        j = high;
        while(i<j)
        {
            while((arr[i]<=arr[pivot])&&(i<high))
            {
                i++;
            }
            while(arr[j]>arr[pivot])
            {
                j--;
            }

            if(i<j)
            {
                temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }

        temp=arr[pivot];
        arr[pivot]=arr[j];
        arr[j]=temp;
        quick_sort(arr,low,j-1);
        quick_sort(arr,j+1,high);
    }
}


Download Code
OUTPUT : 


Cpp - Quick Sort

Cpp Program for sorting elements using merge sort


This a Cpp program which sorts all the elements using Merge Sort Technique.

Merge sort is a divide and conquer technique , here the element list is divided into half and that halves are again divided into halves until only 2 elements left . Then compare those 2 elements , smallest one is kept first, repeat the same process until are the halves are sorted , and repeat the same process but in reverse order to unite the element list into one again.




See the animation below,
Merge-sort-example-300px.gif
"Merge-sort-example-300px" by Swfung8 - Own work. Licensed under CC BY-SA 3.0 via Wikimedia Commons.



Download Code

PROGRAM : 
#include <iostream>
using namespace std;
void mergeSort(int [], int, int, int);
void partition(int [],int, int);
int main()
{
    int list[50];
    int i, n;

    cout << "How many numbers ? \t";
    cin >> n;
    cout << "\n\n";
    for(i = 0; i < n; i++)
    {
        cout << "Enter number  " << i+1 << ":\t";
        cin >> list[i];
    }
    partition(list, 0, n - 1);
    cout << "\n\nAfter merge sort:\n";
    for(i = 0; i < n; i++)
    {
        cout << list[i] << "\t";
    }
    cout << "\n\n";
    return 0;
}
void partition(int list[],int low,int high)
{
    int mid;

    if(low < high)
    {
        mid = (low + high) / 2;
        partition(list, low, mid);
        partition(list, mid + 1, high);
        mergeSort(list, low, mid, high);
    }
}

void mergeSort(int list[],int low,int mid,int high)
{
    int i, midd, k, loww, temp[50];

    loww = low;
    i = low;
    midd = mid + 1;
    while ((loww <= mid) && (midd <= high))
    {
        if (list[loww] <= list[midd])
        {
            temp[i] = list[loww];
            loww++;
        }
        else
        {
            temp[i] = list[midd];
            midd++;
        }
        i++;
    }
    if (loww > mid)
    {
        for (k = midd; k <= high; k++)
        {
            temp[i] = list[k];
            i++;
        }
    }
    else
    {
        for (k = loww; k <= mid; k++)
        {
            temp[i] = list[k];
            i++;
        }
    }

    for (k = low; k <= high; k++)
    {
        list[k] = temp[k];
    }
}


Download Code

OUTPUT : 
Cpp - Merge Sort