Monday, October 15, 2012

Java all data types example


package javaapplication2 ;

import java.util.Date;

  /**
 *
 * @author ASHISH SINGH
 */
class JavaDataType
  {

    public static void main(String[] args)
    {
                //Byte example
                
                 byte b1 = 100;
                 byte b2 = 20;
                
                System.out.println("Value of byte variable b1 is :" + b1);
                System.out.println("Value of byte variable b1 is :" + b2);

                //Charecter Example
               
        char ch1 = 'a';
                char ch2 = 65; /* ASCII code of 'A'*/
              
                System.out.println("Value of char variable ch1 is :" + ch1);  
                System.out.println("Value of char variable ch2 is :" + ch2);     


        //Double example
       
        double d = 1232.44;
                System.out.println("Value of double variable d is :" + d);

        //Float example
       
        float f = 10.4f;
                System.out.println("Value of float variable f is :" + f);

        //Integer example

         int i = 0;
                 int j = 100;
                 System.out.println("Value of int variable i is :" + i);
                 System.out.println("Value of int variable j is :" + j);

        //Long example

        long timeInMilliseconds = new Date().getTime();
                System.out.println("Time in milliseconds is : " + timeInMilliseconds);     

            //Short example

         short s1 = 50;
                 short s2 = 42;
                System.out.println("Value of short variable b1 is :" + s1);
                System.out.println("Value of short variable b1 is :" + s2);

               //Integer to string conversion

       
                i = 11;
                String str = Integer.toString(i);
        System.out.println("int to String : " + i);
          
    }
}


Output

 

Boolean Example in java

public class JavaBooleanExample {
        public static void main(String[] args) 
     {
              
       

                boolean b1 = true;
                boolean b2 = false;
                boolean b3 = (10 > 2)? true:false;
              
                System.out.println("Boolean variable b1 is :" + b1);
                System.out.println("Boolean variable b2 is :" + b2);
                System.out.println("Boolean variable b3 is :" + b3);           
        }
}


Output
 Boolean variable b1 is :true
 Boolean variable b2 is :false
 Boolean variable b3 is :true

Heapsort Algorithm and Source Code


//Heap sort
#include <iostream.h>
#include <conio.h>
const int MAX = 10 ;
class array
{
    private :
        int arr[MAX] ;
        int count ;
    public :
        array( ) ;
        void add ( int num ) ;
        void makeheap(int ) ;
        void heapsort( ) ;
        void display( ) ;
} ;
array :: array( )
{
    count = 0 ;
    for ( int i = 0 ; i < MAX ; i++ )
        arr[MAX] = 0 ;
}
void array :: add ( int num )
{
    if ( count < MAX )
    {
        arr[count] = num ;
        count++ ;
    }
    else
        cout << "\nArray is full" << endl ;
}
void array :: makeheap(int c)
{

    for ( int i = 1 ; i < c ; i++ )
    {
        int val = arr[i] ;
        int s = i ;
        int f = ( s - 1 ) / 2 ;
        while ( s > 0 && arr[f] < val )
        {
            arr[s] = arr[f] ;
            s = f ;
            f = ( s - 1 ) / 2 ;
        }
        arr[s] = val ;
    }
}
void array :: heapsort( )
{
    for ( int i = count - 1 ; i > 0 ; i-- )
    {
        int ivalue = arr[i] ;
        arr[i] = arr[0] ;
        arr[0]=ivalue;
        makeheap(i);

    }
}
void array :: display( )
{
    for ( int i = 0 ; i < count ; i++ )
        cout << arr[i] << "\t" ;
    cout << endl ;
}
int main( )
{
    array a ;

    a.add ( 11 ) ;
    a.add ( 2 ) ;
    a.add ( 9 ) ;
    a.add ( 13 ) ;
    a.add ( 57 ) ;
    a.add ( 25 ) ;
    a.add ( 17 ) ;
    a.add ( 1 ) ;
    a.add ( 90 ) ;
    a.add ( 3  ) ;
    a.makeheap(10) ;
    cout << "\nHeap Sort.\n" ;
    cout << "\n\n\nBefore Sorting:\n"  ;
    a.display( ) ;
    a.heapsort( ) ;
    cout << "\n\n\nAfter Sorting:\n" ;
    a.display( ) ;
    getche();
}


Output

Bubble sort Algorithm and Source Code


#include <stdio.h>
#include <conio.h>

//return p,q in ascending order
void Order(int *p,int *q) {
  int temp;
  if(*p>*q) {
    temp=*p;
    *p=*q;
    *q=temp;
  }
}

//Buuble sorting of integer array A[]
void Bubble(int *a,int n) {
  int i,j;

  for (i=0; i<n; i++)
    for (j=n-1; i<j; j--)
      Order(&a[j-1], &a[j]);

}

int main() {
  int i,j,n=0;
  static int a[20];
  printf("Enter number of item you want to enter=\t\t");
  scanf("%d",&n);
  printf("\n\nEnter the elements=\n");
  for(j=0;j<n;j++)
  {
                  scanf("%d",&a[j]);
  }

  printf("\n\n Initial table A:\n");
  for(i=0; i<n; i++)
    printf(" %d ",a[i]);

  Bubble(a,n);

  printf("\n\n Sorted table A:\n");
  for(i=0; i<n; i++)
    printf(" %d ",a[i]);

  printf("\n\n");
  getche();
}

Output

Merge sort algorithm and source code

#include <stdio.h>
#include <math.h>
#include <conio.h>

  void sort(double *a, int lo, int hi) {

    if (lo>=hi) return; //no action
    int mid = (lo + hi) / 2;

    // Partition the list into two lists and sort them recursively
    sort(a, lo, mid);
    sort(a, mid + 1, hi);

    // Merge the two sorted lists
    int start_hi = mid + 1;
    int end_lo = mid;
    while ((lo <= end_lo) && (start_hi <= hi)) {
      if (a[lo] < a[start_hi])
        lo++;
      else {
      // a[lo] >= a[start_hi]
      // The next element comes from the second list,
      // move the a[start_hi] element into the next
      // position and shuffle all the other elements up.
        double T = a[start_hi];
        for (int k = start_hi - 1; k >= lo; k--) {
          a[k+1] = a[k];
        }
        a[lo] = T;
        lo++;
        end_lo++;
        start_hi++;
      }
    }
  }

int main() {
    int i,n=16;
    static double a[] = {4,3,1,67,55,8,0,4,-5,37,7,4,2,9,1,-1};

    printf("\n\n Initial table A:\n");
    for(i=0; i<n; i++) {
      printf(" %5.2f ",a[i]);
      if(i==7) printf("\n");
    }

    sort(a,0, n-1);

    printf("\n\n Sorted table A:\n");
    for(i=0; i<n; i++) {
      printf(" %5.2f ",a[i]);
      if(i==7) printf("\n");
    }
    printf("\n\n");
    getche();
  }
Output
 

Quicksort Algorithm and Source Code



Quick Sort
Quick sort is a fast sorting algorithm, which is used not only for educational purposes, but widely applied in practice. On the average, it has O(n log n) complexity, making quick sort suitable for sorting big data volumes. The idea of the algorithm is quite simple and once you realize it, you can write quick sort as fast as bubble sort.
Algorithm
The divide-and-conquer strategy is used in quick sort. Below the recursion step is described:
  1. Choose a pivot value. We take the value of the middle element as pivot value, but it can be any value, which is in range of sorted values, even if it doesn't present in the array.
  2. Partition. Rearrange elements in such a way, that all elements which are lesser than the pivot go to the left part of the array and all elements greater than the pivot, go to the right part of the array. Values equal to the pivot can stay in any part of the array. Notice, that array may be divided in non-equal parts.
  3. Sort both parts. Apply quick sort algorithm recursively to the left and the right parts.
Partition algorithm in detail
There are two indices i and j and at the very beginning of the partition algorithm i points to the first element in the array and j points to the last one. Then algorithm moves i forward, until an element with value greater or equal to the pivot is found. Index j is moved backward, until an element with value lesser or equal to the pivot is found. If i ≤ j then they are swapped and i steps to the next position (i + 1), j steps to the previous one (j - 1). Algorithm stops, when i becomes greater than j.
After partition, all values before i-th element are less or equal than the pivot and all values after j-th element are greater or equal to the pivot.
Example. Sort {1, 12, 5, 26, 7, 14, 3, 7, 2} using quicksort. 

Notice, that we show here only the first recursion step, in order not to make example too long. But, in fact, {1, 2, 5, 7, 3} and {14, 7, 26, 12} are sorted then recursively.
Why does it work?
On the partition step algorithm divides the array into two parts and every element a from the left part is less or equal than every element b from the right part. Also a and b satisfy a ≤ pivot ≤ b inequality. After completion of the recursion calls both of the parts become sorted and, taking into account arguments stated above, the whole array is sorted.
Complexity analysis
On the average quick sort has O(n log n) complexity, but strong proof of this fact is not trivial and not presented here. In worst case, quicksort runs O(n2) time, but on the most "practical" data it works just fine and outperforms other O(n log n) sorting algorithms.
Code snippets

#include<iostream.h>
#include<conio.h>
int a[200],l,u,i,j,n;
void quick(int *,int,int);
int main()
{
//clrscr();
cout <<"Enter the number of elements=\t";
cin>>n;
cout <<"\n\nEnter the elements=\t";
for(i=0;i<n;i++)
cin >> a[i];
l=0;
u=n;
cout << " \n\nIteration are \n\n";
quick(a,l,u);
cout <<"\n\n sorted elements\t";
for(i=0;i<n;i++)
cout << a[i+1] << " ";
getch();
}

void quick(int a[],int l,int u)
{
   int p,temp;
   if(l<u)
   {
   p=a[l];
   i=l;
   j=u;
    while(i<j)
   {
      while(a[i] <= p && i<j )
     i++;
      while(a[j]>p && i<=j )
       j--;
      if(i<=j)
      {
      temp=a[i];
      a[i]=a[j];
      a[j]=temp;}
  }
  temp=a[j];
  a[j]=a[l];
  a[l]=temp;
  cout <<"\n";
  for(i=0;i<n;i++)
  cout <<a[i]<<" ";
  quick(a,l,j-1);
  quick(a,j+1,u);
 }
}

 OUTPUT-

Java continue statement with label

public class JavaContinueWithLabelExample {

  public static void main(String[] args) {
  
    int intArray[][] = new int[][]{{1,2},{2,3}};
  
    Outer:
    for(int i=0; i < intArray.length; i++)
    {
      for(int j=0; j < intArray[i].length ; j++)
      {
        if(intArray[i][j] == 3)
          continue Outer;
        System.out.println("Element is : " + intArray[i][j]);
      }
    }
    
  }
}

Output-
Element is : 1
Element is : 2
Element is : 2

Java break statement with label example

    public class JavaBreakWithLableExample

      public static void main(String[] args) {

       

       

        int[][] intArray = new int[][]{{1,2,3,4,5},{10,20,30,40,50}};

        boolean blnFound = false;

       

        System.out.println("Searching 30 in two dimensional int array..");

       

        Outer:

        for(int intOuter=0; intOuter < intArray.length ; intOuter++)

        {

          Inner:

          for(int intInner=0; intInner < intArray[intOuter].length; intInner++)

          {

            if(intArray[intOuter][intInner] == 30)

            {

              blnFound = true;

              break Outer;

            }  

           

          }

        }

       

        if(blnFound == true)

          System.out.println("30 found in the array");

        else

          System.out.println("30 not found in the array");

      }

    }

    Output

    Searching 30 in two dimensional int array..

    30 found in the array

Thursday, October 11, 2012

Swap Numbers Without Using Third Variable Java Example



public class SwapElements{
   
          public static void main(String[] args) {
                 
                  int num1 = 10;
                  int num2 = 20;
                 
                  System.out.println("Before Swapping");
                  System.out.println("Value of num1 is :" + num1);
                  System.out.println("Value of num2 is :" +num2);
                 
                  //add both the numbers and assign it to first
                  num1 = num1 + num2;
                  num2 = num1 - num2;
                  num1 = num1 - num2;
                 
                  System.out.println("After Swapping");
                  System.out.println("Value of num1 is :" + num1);
                  System.out.println("Value of num2 is :" +num2);
          }
   
   
  }
   

  Output
  Before Swapping
  Value of num1 is :40
  Value of num2 is :50
  After Swapping
  Value of num1 is :50
  Value of num2 is :40

Swap Numbers Java Example



  public class SwapElementsExample {
   
          public static void main(String[] args) {
                 
                  int num1 = 10;
                  int num2 = 20;
                 
                  System.out.println("Number Before Swapping");
                  System.out.println("Value of num1 is :" + num1);
                  System.out.println("Value of num2 is :" +num2);
                 
                  //swap the value
                  swap(num1, num2);
          }
   
          private static void swap(int num1, int num2) {
                 
                  int temp = num1;
                  num1 = num2;
                  num2 = temp;
                 
                  System.out.println("Number After Swapping");
                  System.out.println("Value of num1 is :" + num1);
                  System.out.println("Value of num2 is :" +num2);
                 
          }
  }
   
 
  Output
  Number Before Swapping
  Value of num1 is :10
  Value of num2 is :20
  Number After Swapping
  Value of num1 is :20
  Value of num2 is :10