Thursday 16 March 2017

Bubble Sort Logic in C#

What is Bubble Sort ?

Bubble sort is the way of sorting the numeric elements in the collection by traversing through the collection and comparing adjacent elements. The collection is traversed from the beginning. The 1st place element is compared with the 2nd place element and if 1st place element is found to be greater than the 2nd place element then both are swapped (i.e. 2nd place element is moved to the 1st place and 1st place element is moved to 2nd place) and if the pair is already in sorted order then the comparison is done between 2nd place element and 3rd place element, here also swapping is done in case 2nd place element is greater than 3rd place element else the comparison moves to 3rd place element and 4th place element, and this way the comparison moves along throughout the collection between adjacent elements.

The name "bubble" because, the every-time the collection is traversed and comparisons takes place, the largest element is bubbled out.

Cons:
The approach is too slow and takes lot of time for sorting out the elements in case the collection is very large. Not preferred to use for larger collections.

Note: this code is written in visual studio console application, which accepts input from the user via Console.
Input Format: input is taken in two lines. In the 1st line user specifies the no. of elements in the array and in the 2nd line user specifies the those number of elements(mentioned in the 1st line) separated by single space. e.g.
Input Format:
4
8 3 7 4
Output Format:
Array has taken 4 swaps to get sorted.
1st smallest Element: 3
Last largest Element: 8


Bubble Sort in C#


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
    

    static void Main(String[] args) {
        int swapNum = 0;
        int n = Convert.ToInt32(Console.ReadLine());
        string[] a_temp = Console.ReadLine().Split(' ');
        int[] a = Array.ConvertAll(a_temp,Int32.Parse);
        for(int i=0; i<n;i++)
            {
            
            int temp;
            for (int j = 0; j < n - 1; j++) {
        // Swap adjacent elements if they are in decreasing order
        if (a[j] > a[j + 1]) {
            //swap(a[j], a[j + 1]);
            temp = a[j];
            a[j] = a[j+1];
            a[j+1] = temp;
            swapNum++;
        }
    }
    
    // If no elements were swapped during a traversal, array is sorted
    if (swapNum == 0) {
        break;
    }
        }

    Console.WriteLine("Array has taken {0} swaps to get sorted.",swapNum);
        Console.WriteLine("1st smallest Element: {0}",a[0]);
        Console.WriteLine("Last largest Element: {0}",a[n-1]);
    }
}

Saturday 5 March 2016

Static properties

Static properties are meant for the static field-data members, means you can have static property in place in-order to get and set static field-data. There's a separate post for the understanding of static members of the class and the importance of static keyword in C# language.
For the time being just understand that you need not to create object of a class using new keyword( as we use to do in : Company objRef = new Company(); ) to invoke static members of the class, only class reference will do the job.
Example
class Company
{
    // field-data declared private
    private string nameOfCompany;
    private int licenseNumber;

    // Notice the static field-data
    private static double stockPrice;

   //Notice the static property in place to get and set private static field-data stockPrice
   public static double mktStockPrice
   {
     get { return stockPrice; }
     set { stockPrice = value; }
    }

    //property 'Name' to get and set the value
    public string Name
    {
      get
         { return nameOfCompany; }
      set
         {  // check condition before assigning value to private field-data
            if(value.Length < 26)
             nameOfCompany = value;
           else
               Console.WriteLine("Name exceeds maximum limit");
          }
     }
    //similarly property 'LicenseNum' for private field-data licenseNumber
    public int LicenseNum
    {
       get
         { return licenseNumber; }
      set
         { // check condition before assigning value to private field-data
            if(value != 0 && value < 0)
             licenseNumber = value; 
           else
               Console.WriteLine("Invalid License Number");
          }
    }

}
--------------------------------------------------------------------------------------------------
class Program
{
static void Main(string[] args)
{
// object creation of class Company
Company objRef = new Company();

//Notice we used class reference instead of object-reference to set static property //'mktStockPrice'
Company.mktStockPrice = 1181.32;

//here also we used class reference because static members are invoked by class reference
Console.WriteLine("Company name is :  {0}" , Company.mktStockPrice);

Console.ReadLine();
}

}

Note:

Static field-data members are class level or universal kind of members rather than object level, when I say class level and not object level, it means whatever value you set for any static field-data member then that field-data value will be available throughout the objects you create.
As shown in the above example, the value of private field-data 'stockPrice' is set to 1181.32 via static property 'mktStockPrice', now this value remains the same for all the objects you are going to create for the class, because there's only one copy of the static field-data member which works at the class level and all the objects of the class use that single copy of the static field-data. 

Friday 4 March 2016

Read-Only and Write-Only properties

Read-Only property

In some scenarios, there are certain field-data members for which we're interested only in reading value from them. In those scenarios we omit the set { } scope and write only get { } scope.
Example:
class Company
{
    // field-data declared private
    private string nameOfCompany;
    private int licenseNumber;

//customised constructor
public Company(string name; int Num)
{  
   //below statement will produce error as 'Name' is a Read-Only property, so we can't assign    // value through property
   //Name = name;

   // we can still assign nameOfCompany the value by avoiding the use of property here and    //directly assigning value to private field-data
   nameOfCompany = name;

   LicenseNum = Num;
}

    //Notice here 'Name' property is Read-Only property
    public string Name
    {
      get
         { return nameOfCompany; }
     }
    //similarly property 'LicenseNum' for private field-data licenseNumber
    public int LicenseNum
    {
       get
         { return licenseNumber; }
      set
         {  // check condition before assigning value to private field-data
            if(value != 0 && value < 0)
              licenseNumber = value;
           else
               Console.WriteLine("Invalid License Number");
          }
     }

}

Write-Only property

When there's no logic or business rule to be written in set scope of the property then .NET has provided a very short syntax to solve the purpose which comes very handy, just omit the get { } scope from the property syntax.
Example:
class Company
{
    // field-data declared private
    private string nameOfCompany;
    private int licenseNumber;

//customised constructor
public Company(string name; int Num)
{  
   //below statement will produce error as 'Name' is a Read-Only property, so we can't              //assign value through property
   //Name = name;

   // we can still assign nameOfCompany the value by avoiding the use of property here            //and directly assigning value to private field-data
   nameOfCompany = name;

   LicenseNum = Num;
}

    //Notice here 'Name' property is Read-Only property
    public string Name
    {
      get
         { return nameOfCompany; }
     }
    //Notice here the property LicenseNum is a Write-Only property as there's no get{} scope
    public int LicenseNum
    {
      set
         {  // check condition before assigning value to private field-data
            if(value != 0 && value < 0)
              licenseNumber = value;
           else
               Console.WriteLine("Invalid License Number");
          }
     }

}
Therefore if we try to invoke the get { } scope of the property 'LicenseNum' this time, we'll get error.
Example
class Program
{
static void Main(string[] args)
{

Company objRef = new Company("XYZ InfoTech Pvt. Ltd', 12343);

//here we're trying to invoke the get { } scope of the property 'LicenseNum' which will //produce error as it is a 'Write-Only' property
Console.WriteLine("Company license number is :  {0}" , objRef.LicenseNum);

Console.ReadLine();
}

} 

Note:

We can still get the value of private field-data 'licenseNumber', but for that we've to make a new method in class 'Company' which directly accesses the private field-data 'licenseNumber' and thus calling that method from Main(string[] args) can provide us the value of private field-data licenseNumber.
Example
//add the following method in class Company
public void displayLicenseNum()
{
  Console.WriteLine("License Number is : {0}, licenseNumber);
}
Thus call to above written displayLicenseNum() method from Main(string[] args) will provide us the value of private field-data 'licenseNumber'.


Use of property in a class itself where it's been declared

Since we can access private field-data directly in a class where it's been declared, so we kind of have a habit of assigning values directly to these private field-data members in our constructors or any other method in the class.
example: 

class Company
{
    // field-data declared private
    private string nameOfCompany;
    private int licenseNumber;

//customised constructor
public Company( string name; int Num)
{  
   nameOFCompany = name;
   licenseNumber = Num;
}

    //property 'Name' to get and set the value
    public string Name
    {
      get
         { return nameOfCompany; }
      set
         { // check condition before assigning value to private field-data
            if(value.Length < 26)
             nameOfCompany = value;
            else
              Console.WriteLine("Name exceeds maximum limit");
          }
      }
    //similarly property 'LicenseNum' for private field-data licenseNumber
    public int LicenseNum
    {
       get
         { return licenseNumber; }
      set
         {  // check condition before assigning value to private field-data
            if(value != 0 && value < 0)
              licenseNumber = value;
           else
               Console.WriteLine("Invalid License Number");
          }
     }

}
----------------------------------------------------------------------------------
class Program
{
static void Main(string[] args)
{

Company objRef = new Company("XYZ InfoTech Pvt. Ltd', 12343);

//here we're setting the property 'Name' to assign value to private field-data //'nameOfCompany' and it's commented coz the constructor is doing same job
//objRef.Name = "XYZ InfoTech Pvt. Ltd";

//here we're setting the property 'LicenseNumber' to assign value to private field-data //'licenseNumber' and it's commented coz the constructor is doing same job
//objRef.LicenseNum = 12343;

//here we're calling the property 'Name' which further will call the get scope of the property //and returns the value it's supposed to send back
Console.WriteLine("Company name is :  {0}" , objRef.Name);

Console.ReadLine();
}

}
--------------------------------------------------------------------------------------------

Note:

If you notice closely, you'll observe a sense of code duplication, where the constructor and the set scope of the properties have same code, which can be avoided by using the properties in the constructor rather than assigning to the private field-data, which is already happening at set { } scope of the properties( this'll make the re-use the code written at set{ } scope properties)
Therefore the class Company can be modified as:
class Company
{
    // field-data declared private
    private string nameOfCompany;
    private int licenseNumber;

//customised constructor
public Company( string name; int Num)
{  
   //notice now properties are used to assign values to field-data rather than assigning to          //private field-data as done previously
   Name = name;
   LicenseNum = Num;
}

    //property 'Name' to get and set the value
    public string Name
    {
      get
         { return nameOfCompany; }
      set
         { // check condition before assigning value to private field-data
            if(value.Length < 26)
             nameOfCompany = value;
            else
              Console.WriteLine("Name exceeds maximum limit");
          }
      }
    //similarly property 'LicenseNum' for private field-data licenseNumber
    public int LicenseNum
    {
       get
         { return licenseNumber; }
      set
         {  // check condition before assigning value to private field-data
            if(value != 0 && value < 0)
              licenseNumber = value;
           else
               Console.WriteLine("Invalid License Number");
          }
     }

}

This is how we can make use of properties in the class itself where it's been declare, rather wherever value has to be assigned or to get the existing value of private field-data, we can comfortably make use of property syntax avoiding code-duplication.

A public .NET property

Another way of doing encapsulation is using .NET properties. Properties in .NET are nothing but simplification of accessor and mutator methods.
Below shown is same Company class as was shown in previous post but with using property syntax :

class Company
{
    // field-data declared private
    private string nameOfCompany;
    private int licenseNumber;

    //property 'Name' to get and set the value
    public string Name
    {
      get
         { return nameOfCompany; }
      set
         {  // check condition before assigning value to private field-data
            if(value.Length < 26)
             nameOfCompany = value;
           else
               Console.WriteLine("Name exceeds maximum limit");
          }
     }
    //similarly property 'LicenseNum' for private field-data licenseNumber
    public int LicenseNum
    {
       get
         { return licenseNumber; }
      set
         { // check condition before assigning value to private field-data
            if(value != 0 && value < 0)
             licenseNumber = value; 
           else
               Console.WriteLine("Invalid License Number");
          }
    }


}

Note: 

This syntax of property is little compact than writing two separate methods i.e. accessor and mutator methods as shown in the previous post. In-short the syntax is:

public returnType PropertyName
{
get { return field-data; }
set { if( test value) field-data = value; else Console.WriteLine("Sorry");}
}
I highlighted the 'value' keyword in set {  } piece of code, in-order  to stress upon it's importance. When some code set some value by calling the property syntax, then that value is automatically captured by 'value' keyword of the property i.e. there's no need of explicit declaration of temporary variable to store the value and later assign it to field-data as we use to do in mutator method.

class Program
{
static void Main(string[] args)
{
Company objRef = new Company();

//here we're setting the property 'Name' to assign value to private field-data //'nameOfCompany'
objRef.Name = "XYZ InfoTech Pvt. Ltd";

//here we're setting the property 'LicenseNumber' to assign value to private field-data //'licenseNumber'
objRef.LicenseNum = 12343;

//here we're calling the property 'Name' which further will call the get scope of the property //and returns the value it's supposed to send back
Console.WriteLine("Company name is :  {0}" , objRef.Name);

Console.ReadLine();
}
}

This is how the property syntax used in the code.



Exercising Encapsulation through traditional Accessor and Mutator Methods in C#

This is very basic and little lengthy way of exposing private field-data through accessor and mutator methods. In this field-data is declared private and then public accessor and mutator methods are formed through which private field-data can be accessed indirectly.
Example:

class Company
{
    // field-data declared private
    private string nameOfCompany;
    private int licenseNumber;

    //accessor method to get the value
    public string getName()
    {
      return nameOfCompany;
    }

    // mutator method to assign the value to private field-data
    public void setName(string name)
   { 
     // check condition before assigning value to private field-data
     if(name.Length < 26)
     {
        nameOfCompany = name;
     }
     else
    {
     Console.WriteLine("Name exceeds maximum limit");
    }

    //similarly accessor method for private field-data licenseNumber
    public int getLicenseNumber()
    {
      return licenseNumber;
    }

    //similarly mutator method to assign the value to private field-data licenseNumber
    public void setLicenseNumber( int licenseNum ) 
    {
     licenseNumber = licenseNum;
    }

}

Note:
if there're too many field-data members in a class then making accessors and mutators for each of those field-data members makes the code too lengthy, therefore it's not preferable to choose this syntax in case number of field-data members is large.

   

Different ways of accessing encapsulated data

As we saw in the previous post, we encapsulated field-data by prefixing 'private' access modifiers and exposed certain public methods with conditions to access their values or to manipulate their values. The example provided in the previous post can again be seen as follows:

class Company
{
   // made field-data private
   private string nameOfCompany;

   // made a public method to deal with private field-data
   public void setName( string name)
    {
      if(name.Length < 26)
        {
          nameOfCompany = name;
        }
      else
        {
         Console.WriteLine("Sorry name exceeds the character limit");
        }
  }
    //some more methods
}
------------------------------------------------------------------------------------
class Program
{
    public static void Main(string[] args)
     {
        Company objRef = new Company();

         //this piece of line will give error as nameOfCompany is declared private
        //objRef.nameOfCompany = "any name";

        // public method setName(string name) is called to assign value to private field-data
        objeRef.setName( "afdasdfahdfklasjflkhjfkjsdskjdfkasjjflkjk");
     }
}

-------------------------------------------------------------------------------------
In the above given code, setName(string name) method is one of the different ways to access/manipulate the field data. C# language has provided more constructs to access the private field-data, which I'll show in the next section.


Different ways of accessing encapsulated data