Tuesday, 3 December 2019

Sample Programs and Singleton Design Pattern

# include<iostream>
# include<stdio.h>
using namespace std;

class TInstanceCount
{
static int _instanceCount;
public:
TInstanceCount(void)
{
++TInstanceCount::_instanceCount;
}
static int GetInstanceCount(void)
{
return TInstanceCount::_instanceCount;
}
};
int TInstanceCount::_instanceCount=0;

int main(void)
{
TInstanceCount ob1,ob2,ob3,ob4;
int a =ob1.GetInstanceCount();
printf("%d\n",a);
return 0;
}





# include<stdio.h>
# include<iostream>

using namespace std;

class TSingleton
{
private:
int _num1;
int _num2;
private:
TSingleton(const int num1,const int num2):_num1(num1),_num2(num2)
{};
public:
static TSingleton& getInstance(const int num1,const int num2)
{
static TSingleton singletonInstance(num1,num2);
return singletonInstance;
}

void PrintRecord(void)
{
cout<<"Num1 : "<<this->_num1<<endl;
cout<<"Num2 : "<<this->_num2<<endl;
}
};
int main(void)
{
TSingleton& s1=TSingleton::getInstance(500,600);
s1.PrintRecord();
TSingleton& s2=TSingleton::getInstance(100,200);
s2.PrintRecord();
return 0;
}





# include<iostream>
# include<stdio.h>
using namespace std;
class TSingleton
{
int _num1;
int _num2;
static TSingleton* _ptr;

private:
TSingleton(const int num1,const int num2):_num1(num1),_num2(num2)
{ }
public:
static TSingleton* getInstance(const int num1,const int num2)
{
if(TSingleton::_ptr==NULL)
{
TSingleton::_ptr=new TSingleton(num1,num2);
return TSingleton::_ptr;
}

}
void printRecord(void)
{
cout<<"NUm1 : "<<this->_num1<<endl;
cout<<"Num2 : "<<this->_num2<<endl;
}
static void clear(void)
{
if(TSingleton::_ptr!=NULL)
delete TSingleton::_ptr;
TSingleton::_ptr=NULL;
}
};
TSingleton* TSingleton::_ptr=NULL;
int main(void)
{
TSingleton* ptr1=TSingleton::getInstance(100,200);
TSingleton* ptr2=TSingleton::getInstance(500,600);
ptr1->printRecord();
ptr2->printRecord();
TSingleton::clear();
return 0;
}


# include<stdio.h>
# include<iostream>
using namespace std;

int sum(int num1,int num2)
{
return num1+num2;
}
int sub(int num1,int num2)
{
return num1-num2;
}

int menu_list(void)
{
int choice;
cout<<"0.Exit"<<endl;
cout<<"1.Sum"<<endl;
cout<<"2.Sub"<<endl;
cout<<"Enter Choice: ";
cin>>choice;
return choice;
}

void accept_record(int & number)
{
cout<<"Enter Number : ";
cin>>number;
}
void print_record(const int& result)
{
cout<<"Result :"<<result<<endl;
}
int main(void)
{
int choice;
int num1,num2;
while((choice=::menu_list())!=0)
{
int(*ptr)(int,int)=NULL;
int result=0;
switch(choice)
{
case 1:
ptr=&sum;
break;
case 2:
ptr=&sub;
break;
}
if(ptr!=NULL)
{
::accept_record(num1);
::accept_record(num2);
result=ptr(num1,num2);
::print_record(result);
}
}
return 0;
}




Sample Programs

# include<iostream>
using namespace std;

class Test
{
private:
int num1;
static const int num2;
public:
Test(void)
{
this->num1=10;
}
void PrintRecord(void)
{
cout<<"Num1 : "<<this->num1<<endl;
cout<<"Num2 : "<<this->num2<<endl;
}
};
const int Test::num2=1000;
int main(void)
{
Test t1;
t1.PrintRecord();
return 0;
}




# include<iostream>
using namespace std;

class A
{
public:
static void F1(void)
{
cout<<"A::F1"<<endl;
}
};

class B
{
public:
static void F2(void)
{
cout<<"B::F2"<<endl;
}
static void F3(void)
{
A::F1();
F2();
B::F2();
cout<<"B::F3"<<endl;
}
};

int main(void)
{
B::F3();
return 0;
}



# include<iostream>
using namespace std;
#include <string>

namespace NEmployee
{
class TEmployee
{
private:
string _name;
int _empid;
float _salary;
static int _count;
public:
TEmployee(void)
{
this->_name=" ";
this->_empid=++TEmployee::_count;
this->_salary=0;
}
TEmployee(const string name,const float salary)
{
this->_name=name;
this->_empid= ++TEmployee::_count;
this->_salary=salary;
}
static void SetCount(int count)
{
TEmployee::_count=count;
}
void PrintRecord()
{
cout << this->_name<<" "<<this->_empid<<" "<<this->_salary << "\n";
}
};
int TEmployee::_count;
int main(void)
{
using namespace NEmployee;
TEmployee::SetCount(1000);
TEmployee emp1("ABC",10000.00f);
emp1.PrintRecord();
return 0;
}




# include<iostream>
using namespace std;
#include<string>

class TPerson
{
private:
string _name;
int _age;

public:
TPerson(void)
{
this->_name="";
this->_age=0;
}
TPerson(const string name,const int age):_name(name),_age(age)
{}
void PrintRecord(void)const
{
cout<<"Name: "<<this->_name<<endl;
cout<<"Age: "<<this->_age<<endl;
}
};
class TEmployee:public TPerson
{
private:
int _empid;
float _salary;
public:
TEmployee(void):_empid(0),_salary(0)
{}
TEmployee(const string name,const int age,const int empid,const int salary):TPerson(name,age),_empid(empid),_salary(salary)
{}
void PrintRecord(void)const
{
TPerson::PrintRecord();
cout<<"EmpId: "<<this->_empid<<endl;
cout<<"Salary: "<<this->_salary<<endl;
}

};
int main(void)
{
TEmployee emp("ABC",23,123,1200);
emp.PrintRecord();
return 0;
}


Sunday, 1 December 2019

Sorting Algorithm

/***************************************************
 * Author : Ajit
 *
 * Description : This file contains implementation of selection sort and insertion sort Algorithm
 *
 /**************************************************/


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace Sorting_Techniques
{
    class Sorting
    {

        /*****************************************************************************/
        /* Method Print
        /*
        /* Description This functions prints the array elements .
        /*
        /* Paremeters  int[] a -array elemets to be printed
                       n - No of elements in Array
        /* Return Void
        /******************************************************************************/

        public static void print(int[] a, int n)
        {
            Console.Write("ARR: ");
            for (int i = 0; i < n; i++)
            {
                Console.Write(a[i]);
                Console.Write(' ');
            }
            Console.Write("\n");
        }

        /*****************************************************************************/
        /* Method Selection Sort
        /*
        /* Description This functions sorts the array elements .
           In a set oF N elements find out the location of the minimum elements and replace it with the location of first element.
           Repeat above step for N-1 elements untill the list is sorted.
        /*
        /* Paremeters  int[] a -array to be sorted
                       n - No of elements in Array
        /* Return Void
        /******************************************************************************/
        public static void selection(int[] a, int n)
        {
            int i;
            int j;
            for (i = 0; i < n - 1; i++)
            {
                for (j = i + 1; j < n; j++)
                {
                    if (a[i] > a[j])
                    {
                        int t = a[i];
                        a[i] = a[j];
                        a[j] = t;
                    };
                }
            }
        }

        /*****************************************************************************/
        /* Method Insertion Sort
        /*
        /* Description This functions sorts the array elements .
           A sublist or Sorted array is maintained which is always sorted .
           N-1 pass are required to sort N elements.
           In each pass , we insert current element at appropriate place so that the elements in current range are in order .s
           Each pass has k comparison where k is the pass no.
        /*
        /* Paremeters  int[] a -array to be sorted
                       n - No of elements in Array
        /* Return Void
        /******************************************************************************/

        public static void insertion(int[] a, int n)
        {
            int i;
            int j;
            int temp;
            for (i = 1; i < n; i++)
            {
                temp = a[i];
                for (j = i - 1; j >= 0 && a[j] > temp; j--)
                {
                    a[j + 1] = a[j];
                }
                a[j + 1] = temp;
            }
        }

        public static int RandomNumber(int min, int max)
        {

            Random random = new Random(DateTime.Now.Ticks.GetHashCode());
            return random.Next(min,max);
        }

        static void Main(string[] args)
        {
            Stopwatch myTimer = new Stopwatch();

            /*  Already Sorted Array*/
            int [] arr_sel_asc =new int [500];
            for (int i = 0; i <= arr_sel_asc.Length-1; i++)
                arr_sel_asc[i] = i;
            int[] arr_ins_asc = new int[500];
            for (int i = 0; i <= arr_ins_asc.Length-1; i++)
                arr_ins_asc[i] = i;

            Console.WriteLine("Array before Sorting");
            print(arr_sel_asc, 500);
            myTimer.Start();
            /* Calling Selection Sort Method for Sorted Array*/
            selection(arr_sel_asc, 500);
            myTimer.Stop();
            Console.WriteLine("Time Taken for Selection Sort for Sorted Array : {0}  ", myTimer.Elapsed);
            Console.WriteLine("Array After Selection Sort");
            print(arr_sel_asc, 500);
            myTimer.Reset();
            myTimer.Start();
            insertion(arr_ins_asc, 500);
            myTimer.Stop();
            Console.WriteLine("Time Taken for Insertion Sort for sorted Array : {0}  ", myTimer.Elapsed);
            Console.WriteLine("Array After Insertion Sort");
            print(arr_ins_asc, 500);

            /* Sorted In Opposite Order */

            int[] arr_sel_desc = new int[500];
            for (int i = arr_sel_desc.Length-1; i >=0; i--)
                arr_sel_desc[i] = arr_sel_desc.Length - 1 - i;
            int[] arr_ins_desc = new int[500];
            for (int i = arr_ins_desc.Length-1; i >=0 ; i--)
                arr_ins_desc[i] = arr_sel_desc.Length - 1 - i;

            Console.WriteLine("Array before Sorting");
            print(arr_sel_desc, 500);
            myTimer.Reset();
            myTimer.Start();
            /* Calling Selection Sort Method for Sorted Array in opposite order*/
            selection(arr_sel_desc, 500);
            myTimer.Stop();
            Console.WriteLine("Time Taken for Selection Sort for Sorted Array in Opposite order : {0}  ", myTimer.Elapsed);
            Console.WriteLine("Array After Selection Sort");
            print(arr_sel_desc, 500);
            myTimer.Reset();
            myTimer.Start();
            insertion(arr_ins_desc, 500);
            myTimer.Stop();
            Console.WriteLine("Time Taken for Insertion Sort for sorted Array in Opposite Order : {0}  ", myTimer.Elapsed);
            Console.WriteLine("Array After Insertion Sort");
            print(arr_ins_desc, 500);


            /* Array element in Random Order*/
            int[] arr_ran = new int[500];
            for (int i = 0; i <= arr_ran.Length-1; i++ )
            {
                arr_ran[i] = RandomNumber(1, 500);
            }

            int[] arr_ran_sel = new int[500];

            for (int i = 0; i <= arr_ran_sel.Length-1; i++)
            {
                arr_ran_sel[i] = arr_ran[i];
            }

            int[] arr_ran_ins = new int[500];

            for (int i = 0; i <= arr_ran_ins.Length - 1; i++)
            {
                arr_ran_ins[i] = arr_ran[i];
            }

            Console.WriteLine("Array before Sorting");
            print(arr_ran_sel, 500);
            myTimer.Reset();
            myTimer.Start();
            /* Calling Selection Sort Method for Sorting array elements in random order*/
            selection(arr_ran_sel, 500);
            myTimer.Stop();
            Console.WriteLine("Time Taken for Selection Sort for Sorting array elements in Random order : {0}  ", myTimer.Elapsed);
            Console.WriteLine("Array After Selection Sort");
            print(arr_ran_sel, 500);
            myTimer.Reset();
            myTimer.Start();
            /* Calling Insertin Sort Method for Sorting array elements in Random order*/
            insertion(arr_ran_ins, 500);
            myTimer.Stop();
            Console.WriteLine("Time Taken for Insertion Sort for sorting array elements in Random Order : {0}  ", myTimer.Elapsed);
            Console.WriteLine("Array After Insertion Sort");
            print(arr_ran_ins, 500);

            Console.ReadKey();
        }
    }
}


Insertion sort perform less comparison than selection sort  depending on the degree of sortedness
of array.Selection sort must scan the remaining parts of the array when placing an element .Insertion sort only scans as many elements as necessary.
When array is already sorted or almost sorted , insertion sort performs in O(n) Time.
Overall insertion sort usually more efficient.
Below image shows time take by insertion sort and selection sort when array is sorted.





Below image Shows time taken by selection sort and insertion sort when arrays is in opposite order(Descending order).




Below image shows time taken by insertion sort and selection sort when arrays element in Random Order. 







Insertion Sort :

The data is sorted by inserting the data into a sorted location.
Insertion sort perform less comparison than selection sort  depending on the degree of sortedness  of array. 
The  time taken by insertion sort would be dependent on the input .Because sorting thousand numbers takes more time thant sorting 3 numbers .More over it is dependent on how the input is sorted .
But the runnig time of program grows with the size of input.

Assumptions:
Costant amount of time is required to execute each line of pseudocode .

for (i = 1; i < n; i++)                   //Execute N times    //Cost C1          
              {
                temp = a[i];                            //Execute N-1 times   //Cost C2
                for (j = i - 1; j >= 0 && a[j] > temp; j--)   //Execute minimum N-1 Times
                                                       //Execute maximum N(N-1)/2 Times
                                                       //Cost C3    
                {
                    a[j + 1] = a[j];                   //Execute maximum N(N-1)/2 Times 
                                                       //Cost C4
                }
                a[j + 1] = temp;                        //Execute N-1 times Cost C5
          }
As per above observation please find below time complexity
Best case complexity : O(n)
Worst Case: O(n^2)


Selection Sort :

The data is sorted by selecting and placing the consecutive elements in sorted location.
Selection sort must scan the remaining parts of the array when placing an element .

            for (i = 0; i < n - 1; i++)           //Execute N times    //Cost C1          
            {
                for (j = i + 1; j < n; j++)    //Execute N(N-1)/2 Times
                                                       //Cost C2    
                {
                    if (a[i] > a[j])           
                    {
                        int t = a[i];         //Execute N-1 times //Cost C3
                        a[i] = a[j];          //Execute N-1 times //Cost C3
                        a[j] = t;             //Execute N-1 times //Cost C3
                    };
                }
            }
      
Best Case complexity: O(n^2)
Worst Case Complexity : O(n^2)

Insertion sort is more efficient because you have to search the sorted section where the next element goes where as in selection sort you have to scan the entire unsorted part of the array.