Showing posts with label fundamentals in java. Show all posts
Showing posts with label fundamentals in java. Show all posts

Monday, November 10, 2014

Quick Sort (Part- 4)

REFERENCE : PANIMALAR ENGINEERING COLLEGE NOTES
Quick Sort:
Quick sort is one of the most efficient internal sorting technique. It possess a very good average behavior among all the sorting techniques. It is also called as partitioning sort which uses divide and conquer techniques.
                The quick sort works by partitioning the array A[1], A[2]. . . A[N] by picking some key value in the array as a pivot element.Pivot element is used to rearrange the elements in a array. Pivot element can be the first element of an array and the rest of the elements are moved so that elements on left side of the pivot are lesser than the pivot, whereas those on the right sie are greater than the pivot. Now the pivot element is placed in the correct position. Now the quick sort procedure is applied for left array and right array in a recursive manner.

void qsort (int A[ ] , int left, int right)
{
int i,j, temp, pivot;
if(left{
pivot = left;
i = left + 1;
j = right;
while(i{
while(A[pivot]>=A[j])
i++;
while(A[pivot]j--;
if(i{
temp=A[j];
A[i]=A[j];
A[j]=temp;
}
}
temp = A[pivot];
A[pivot] = A[j];
A[j]=temp;
qsort(A,left,j-1);
qsort(A,j+1,right);
}
}

Example: Consider an unsorted array as follows40         20         70          14          60           61            97          30Here pivot = 40

40      20      70      14      60      61      97      30

40      20      70      14      60      61      97      30


40      20      30      14      60      61      97      70

Pass 1:

14      20      30      40      60      61      97      70

Now the pivot element reached its correct position. The elements lesser than pivot {14     20       30} is considered as left sub array. The elements than the pivot { 60     61     97     70} is considered as right sub array. Then the Qsort procedure is applied recursively for both these arrays.

Analysis of Quick Sort

Worst Case Analysis                 - O(N2)
Best Case Analysis                   - O (N log N)
Average Case Analysis              - O (N log N)

Advantages of Quick Sort

It is faster than other O(N log N) algorithms.
It has better cache performance.

Limitations

It requires extra memory space.
It requires more processing time.

Merge Sort Part- 3 REFERENCE : PANIMALAR ENGINEERING COLLEGE NOTES

The most common algorithm used is the merge sort. This algorithm follows divide and conquer strategy. In dividing phase the problem is divided into smaller problem and solved recursively.In conquering phase, the partitioned array is merged together recursively. Merge sort is applied to the first half and second half of the array. This gives two sorted halves which can then be recursively merged together using the merging algorithm.
The basic merging algorithm takes two input arrays A and B and an output array C. The first element of A array and B array are compared, then the smaller element is stored in the output array C and the corresponding pointer is increment. When either input array is exhausted the remainder of the other array is copied to an output array C.

void MSort (ElementType A[ ] , ElementType TmpArray[ ] , int left, int right)
{
int center;
if(left{
center = (left + right) / 2;
msort(A, TmpArray, left,center);
msort(A,TmpArray, center+1,right);
merge(A, TmpArray, left, center+1, right);
}
}

void merge(int A[ ], int TmpArray[ ], int lpos, int rpos, int rightend)
{
int i, num, leftend, tmpos;
leftend = rpos - 1;
tmpos = lpos;
num = rightend - lpos + 1;
while(lpos<=leftend) &&(rpos<=rightend)
if(A[lpos]<=A[rpos])
TmpArray[tmpos++]=A[lpos++];
else
TmpArray[tmpos++]=A[rpos++];
while(lpos<=leftend)
TmpArray[tmpos++]=A[lpos++];
while(rpos<=rightend)
TmpArray[tmpos++] = A[rpos++];
for(i=0;i<=num; i++, rightend--)
A[rightend]=TmpArray[rightend];
}

void MergeSort(ElementType A[ ], int N)
{
ElementType TmpArray[MAX];
MSort (A,TmpArray,0,N-1)
}

The merge sort algorithm is therefore easy to describe. If N-1, there is only one element to sort and the answer is at hand. Otherwise, recursively merge sort the first half and second half. This gives two sorted halves, which can then be merged together using merging algorithm.

For example to sort the eight element array 24, 23, 26, 1, 2, 27, 38, 15. We recursively sort the first four and the last four elements, obtaining 1, 13, 14, 26, 2, 15, 27, 38. Then we merge the two halves as above, obtaining the final list 1, 2, 13, 15, 24, 26, 27, 38.


Analysis of Merge Sort

                   Worst Case Analysis       --  O(NlogN)
                    Best Case Analysis         -- O(NlogN)
                    Average Case Analysis   -- O(NlogN)

Advantages of Merge Sort
It is efficient for sorting large number of elements.
It is simple than Heap sort.
It has better cache performance.
It has the advantages of worst case O(NlogN) running time.

Limitations

It requires more memory space.
It requires more processing time.

Thursday, November 6, 2014

SOME VERY SIMPLE AND BASIC JAVA SOURCE CODES THAT I DEVELOPED. FEEL FREE TO POINT OUT ERRORS IF ANY.(PART-2)

SOURCE CODE #6
//A SIMPLE JAVA PROGRAM THAT EXPLAINS HIERARCHIAL INHERITANCE
/* HERE InheritanceOne is the base calss, Truck, Airplane & Boat are all derived classes.
 * constructor is used in all the classes.
 * The keyword "extends" is used to show that Inheritance concept is used here.
 * Every method prints a simple line on the screen.
 * The output shows the flow of control throughtout the source code.
 * I hope this explains the concept of hierarchial inheritance very well.
 * Author - Hemapriya Gopal
 */

public class InheritanceOne
{
 float position;
 float speed;
 float fuellevel;
 public InheritanceOne()
 {
        System.out.println("Inside the constructor of the base class");
 }
 public void move()
 {
        System.out.println("Inside the InheritanceOne class move() method ");
 }
 public void addPassenger()
 {
        System.out.println("Inside the InheritanceOne class addPassenger() method ");
 }
 public void displayPosition()
 {
        System.out.println("The position of the vehicle is 45' NE ");
 }
 public void displaySpeed()
 {
        System.out.println("The vehicle is moving at the speed of 60km/hr ");
 }
 public void displayFuellevel()
 {
        System.out.println("The fuel tank in the vehicle is half-full");
 }
 public static void main(String args[])
 {
        InheritanceOne io = new InheritanceOne();
        io.move();
        io.addPassenger();
        Airplane a = new Airplane();
        a.operateUnderCarriage();
        a.displayFuellevel();
        Truck t = new Truck();
        t.getTyrePressure();
        t.displaySpeed();
        Boat b = new Boat();
        b.displayPosition();
        b.dock();
 }
/* InheritanceOne()
{
       System.out.println("Inside the destructor of the base class");
}
*/
}
class Airplane extends InheritanceOne
{
       float heightfromGround;
       public Airplane()
       {
              //super();
              System.out.println("Inside the constructor of the derived class Airplane");
       }
       public void operateUnderCarriage()
       {
              System.out.println("Inside the derived class Airplane in the method operateUndercarriage");
       }
}
class Truck extends InheritanceOne
{
       public void getTyrePressure()
       {
              System.out.println("Inside the method getTyrePressure() of the class Truck");
       }
       public Truck()
       {
              System.out.println("Inside the constructor of the derived class Truck");
       }
}
class Boat extends InheritanceOne
{
       public void dock()
       {
              System.out.println("Inside the method dock() of the derived class Boat");
       }
       public Boat()
       {
              System.out.println("Inside the constructor of the derived class Boat");
       }
}

HIERARCHIAL INHERITANCE


OUTPUT:
Inside the constructor of the base class
Inside the InheritanceOne class move() method
Inside the InheritanceOne class addPassenger() method
Inside the constructor of the base class
Inside the constructor of the derived class Airplane
Inside the derived class Airplane in the method operateUndercarriage
The fuel tank in the vehicle is half-full
Inside the constructor of the base class
Inside the constructor of the derived class Truck
Inside the method getTyrePressure() of the class Truck
The vehicle is moving at the speed of 60km/hr
Inside the constructor of the base class
Inside the constructor of the derived class Boat
The position of the vehicle is 45' NE
Inside the method dock() of the derived class Boat


SOURCE CODE #7

/*A very simple program implementing all the basic concepts of javax.swing
 * Reference - 1.The Complete Refernce 5th Edition --Herbert Schildt
 *          2.NUS - ISS S.E Notes for OOP
 *         3.http://www.wattpad.com/6660884-java-swing-gui-development-chapter-two-your-first
 * Author - Hemapriya Gopal
 */
import java.awt.*;
import javax.swing.*;
public class SwingHelloWorldForPractice
{
       public void FrameOne()
       {
              JFrame frame = new JFrame ("Hello World Application");
              frame.setSize(270,70);
              frame.setLayout(new FlowLayout());
             
              JLabel label = new JLabel ("Hello world");
              JButton button = new JButton ("OK");
              frame.add(label);
              frame.add(button);
             
              frame.setVisible(true);
       }
       public void OddOrEvenUsingGUI()
       {
              String num = JOptionPane.showInputDialog (null,"Enter a number");
              int num1=Integer.parseInt(num);
              if(num1==0)
              {
                     JOptionPane.showMessageDialog (null, "The number entered is zero");
              }
              else if(num1 %2 ==0)
              {
                     JOptionPane.showMessageDialog(null, "The number entered is an even number");
              }
              else
              {
                     JOptionPane.showMessageDialog(null, "The number entered is a odd number");
              }
       }
       public void HelloWorldGUI()
       {
              JOptionPane.showMessageDialog(null,"Hello World!", "Hello",JOptionPane.PLAIN_MESSAGE);
       }
public static void main(String args[])
{
       SwingHelloWorldForPractice shwfp = new SwingHelloWorldForPractice();
       shwfp.HelloWorldGUI();
       shwfp.OddOrEvenUsingGUI();
       shwfp.FrameOne();   
}}

OUTPUT:





Wednesday, November 5, 2014

SOME VERY SIMPLE AND BASIC JAVA SOURCE CODES THAT I DEVELOPED. FEEL FREE TO POINT OUT ERRORS IF ANY.

SOURCE CODE #1
//A simple program to find the sum of all natural numbers till 100 (0,100)
public class SumTillHundred
{
public static void main(String args[])
{
int i;
int digit;
for (i=1 , digit = 0; i<=100;i++)
{
digit=digit+i;
}
System.out.println("The sum of natural numbers till 100 = " + digit);
}
}

OUTPUT FOR SOURCE CODE #1
The sum of natural numbers till 100 = 5050

SOURCE CODE #2
//A simple program to find the product of all even positive numbers less than ten
public class ProdEvenLessThanTen 
{
public static void main(String args[])
{
int n;
int digit=1;
for(n=2;n<10 n="" p="">
if(n%2==0)
digit=digit*n;
System.out.println("The product of all even numbers less than 10 is " + digit);
}
}

OUTPUT FOR SOURCE CODE #2
The product of all even numbers less than 10 is 384

SOURCE CODE #3
//A Simple java program that reads a line from keyboard and outputs "Hello"+name
import java.io.*;
public class HelloPlusName 
{
public static void main(String args[]) throws java.lang.Exception
{
System.out.println("Enter your name");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name = br.readLine();
System.out.println("Hello " + name);
}
}

OUTPUT FOR SOURCE CODE #3
Enter your name
Hemapriya
Hello Hemapriya

SOURCE CODE #4
//A simple program that appends firstname with surname and prints the output as "welcome + fullname"
import java.io.*;
import java.lang.String;
public class SurnamePlusFirstname {
public static void main (String args[])throws Exception
{
System.out.println("Enter your firstname \n");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String firstname = br.readLine();
System.out.println("Enter your surname \n");
BufferedReader br2 = new BufferedReader(new InputStreamReader(System.in));
String lastname = br2.readLine();
StringBuilder fullname = new StringBuilder();
fullname.append(firstname); 
fullname.append(lastname);
System.out.println("Welcome " + fullname + "!");
}
}

OUTPUT FOR SOURCE CODE #4
Enter your firstname 

Hemapriya
Enter your surname 

Gopal
Welcome HemapriyaGopal!

SOURCE CODE #5
//Program to find the slope of a straight line in XY- axes when the equation is given
//Assumption: THE SIMPLE CASE THAT THE STRAIGHT LINE INTERSECTS BOTH THE AXES
import java.io.*;
public class SlopeOfStraightLine {
public static void main(String args[]) throws Exception 
{
System.out.println("Enter the equation of the straight line in the two dimensional axes");
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
String eqn = br.readLine();
System.out.println("Enter the co-efficient of x \n");
BufferedReader br1 = new BufferedReader(new InputStreamReader (System.in));
String str1 = br1.readLine();
float coex = Integer.parseInt(str1);
System.out.println("Enter the co-efficient of y \n");
BufferedReader br2 = new BufferedReader(new InputStreamReader (System.in));
String str2 = br2.readLine();
float coey = Integer.parseInt(str2);
float slope = -(coey/coex);
System.out.println("The straight line having the equation " + eqn + " has the slope value of " + slope + "\n");
}
}

OUTPUT FOR SOURCE CODE #5
Enter the equation of the straight line in the two dimensional axes
2X-3Y+6=0
Enter the co-efficient of x 

2
Enter the co-efficient of y 

-3
The straight line having the equation 2X-3Y+6=0 has the slope value of 1.5