Merge Sort


 Merge Sort 


Merge Sort:

  •        Break the list into halves until each piece has one item.
  •        Sort the pieces (they are already sorted because they are single items).
  •        Join pieces back together in sorted order.

 

Merge Sort Algorithm (Plain English)

  1.        If the list has zero or one item, it is already sorted.
       → Just return it.
  2.        If the list has more than one item:
    • Find the middle point of the list.
    • Split the list into two smaller lists:
      left half and right half.
    • Sort the left half by repeating the merge sort steps.
    • Sort the right half by repeating the merge sort steps.
  3.        After both halves are sorted, combine them back together in the correct order using the merge steps.
  4.        Return the final sorted list.

Merge (joining two sorted lists) — Plain English Steps

  1.        Start with two lists that are already sorted.
  2.        Create an empty list to store the result.
  3.        Look at the first item in each list.
  4.        Pick the smaller one and put it into the result list.
  5.        Remove that item from its list.
  6.        Repeat the comparison until one list becomes empty.
  7.        When one list has no more items, add everything left from the other list to the result.
  8.        The result is now a fully sorted list.

 

 

# Merge sort

# Function to merge sorted lists
def merge(a, b):
    c = []
    while (len(a) != 0 and len(b) != 0):
        if a[0] < b[0]:
            c.append(a[0])
            a.remove(a[0])
        else:
            c.append(b[0])
            b.remove(b[0])
    if(len(a) == 0):
        c = c + b
    else:
        c += a
    return c

# Function - create sublists
def mergesort(L1):
    if len(L1) == 0 or len(L1) == 1:
        return L1
    else:
        middle = len(L1)//2
        a = mergesort(L1[:middle])
        b = mergesort(L1[middle:])

    return merge(a,b)

# Read elements and create list
Original_List = eval(input("Enter list of elements : "))
Sorted_list = mergesort(Original_List)

print("Original list :", Original_List)
print("Sorted List :", Sorted_list)

Types of Inheritance

 Inheritance in Java
 

Java Inheritance is a fundamental concept in Object-Oriented Programming. It is the mechanism in Java by which one class is allowed to inherit the features (fields and methods) of another class – creating new classes based on existing ones. A class that inherits from another class can reuse the methods and fields of that class.

Keywords:

    •    Super Class / Parent Class: The class whose features are inherited is known as a superclass (or a base class or a parent class).
    •     Sub Class / Child Class: The class that inherits from the parent class is known as a subclass (or a derived class, extended class or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
    •       extends: The keyword is used to inherit properties from a superclass.

 

Syntax

class <sub_class_name> extends <super_class_name>

{

         // Additional fields and methods

}

 

Need for Inheritance

Inheritance is required in Java to reuse code efficiently, build hierarchical structures, and allow objects to share and extend behavior. It provides a structured way to avoid duplication and improve maintainability.

1.   Code Reusability

2.   Avoid Code Duplication

3.   Method Overriding (Polymorphism) – Change existing features

4.   Extensibility — Easier to Add New Features

5.   Improves Maintainability and Scalability


Types of Inheritance

1.   Simple Inheritance – A sub-class is derived from only one super class. It inherits the properties and behavior of a single-parent class. 

(Super class / parent class)

(Sub class / child class)

2. Multilevel Inheritance - Multilevel Inheritance has one superclass and one subclass and one or more intermediate classes. The intermediate class is both a subclass and superclass – It inherits from the parent class and acts as a parent class to another sub class.

(Super class / Parent class)

 

(Intermediate class. B is a sub class of A and super class of C)

 

(Sub class / Child class)

3. Hierarchical Inheritance - More than one subclass is inherited from a single base class. i.e. more than one derived class is created from a single base class.

 

A – Super class / Parent class

 

 

 

 

B and C – Sub class / Child class

4. Hybrid Inheritance – A mix of two or more types of Inheritance.

 

§  B inherits from A – Simple inheritance

 

§  B and C inherits from A – Hierarchical inheritance

 

§  C inherits from A, D inherits from C – Multilevel inheritance  

 


Hierarchical Inheritance

 Hierarchical Inheritance


// Hierarchical Inheritance

 

class A

{

         void fnDisplay()

         {

                 System.out.println("Hello");

         }

}

 

class B extends A

{

         void fnShow()

         {

                 System.out.println("Welcome");

         }

}

 

class C extends A

{

         void fnPrint()

         {

                 System.out.println("Hai");

         }

}

 

class Inheritance_Demo

{

         public static void main(String as[])

         {

                 B obj1 = new B();

                 obj1.fnDisplay();

                 obj1.fnShow();

                

                 C obj2 = new C();

                 obj2.fnDisplay();

                 obj2.fnPrint();

         }

}       


// Sample Output

>javac Inheritance_Demo.java

>java Inheritance_Demo


Hello

Welcome


Hello

Hai


Multilevel Inheritance


 Multilevel Inheritance





// Multilevel Inheritance

 

class A

{

         void fnDisplay()

         {

                 System.out.println("Hello");

         }

}

 

class B extends A

{

         void fnShow()

         {

                 System.out.println("Welcome");

         }

}

 

class C extends B

{

         void fnPrint()

         {

                 System.out.println("Hai");

         }

}

 

class Inheritance_Demo

{

         public static void main(String as[])

         {

                 C obj = new C();

                 obj.fnDisplay();

                 obj.fnShow();

                 obj.fnPrint();

         }

}      



// Sample output


>javac Inheritance_Demo.java

>java Inheritance_Demo

Hello

Welcome

Hai

Simple Inheritance

 

Simple Inheritance


// Simple Inheritance


class A

{

void fnDisplay()

{

System.out.println("Hello");

}

}


class B extends A

{

void fnShow()

{

System.out.println("Welcome");

}

}


class Inheritance_Demo

{

public static void main(String as[])

{

B obj = new B();

obj.fnDisplay();

obj.fnShow();

}

}





// Sample Output

>javac Inheritance_Demo.java

>java Inheritance_Demo

Hello

Welcome

Event Handling - Mouse events

 
Event Handling - Mouse events 


// JavaFX controls and event handling 

// Mouse events - moved and clicked


import javafx.application.*;

import javafx.stage.*;

import javafx.scene.*;

import javafx.scene.layout.*;

import javafx.scene.control.*;

import javafx.scene.input.*;

import javafx.event.*;

import javafx.geometry.*;


public class  EventHandling_Demo extends Application

{     


   public static void main(String[] as)

   {

        // Start the JavaFX application by calling launch().

        launch(as);

   }


   // Override the start() method.

   public void start(Stage myStage)

   {           

        // Give the stage a title.

        myStage.setTitle("JavaFx - Mouse Event handling");


        // Use a FlowPane for the root node.

        FlowPane fp = new FlowPane(Orientation.VERTICAL,25,25);


        // Center the controls in the scene.

        fp.setAlignment(Pos.CENTER);

       

        // Creating a heading and response text

        Label L1 = new Label("Event Handling - Mouse Events.");


        Label L2 = new Label("");

Label L3 = new Label("");

      

        // Add to the scene graph.

        fp.getChildren().addAll(L1, L2, L3);

     

        // Create a scene.

        Scene myScene = new Scene(fp, 300, 100);


        // Set the scene on the stage.

        myStage.setScene(myScene); 

       

        // Event Handling       

        myScene.setOnMouseMoved(new EventHandler<MouseEvent>(){

             public void handle(MouseEvent me)

             {  

                 L2.setText("Mouse Coordinates : ("+me.getSceneX() + ", "+me.getSceneY()+")");

             }

        } );

   

        myScene.setOnMouseClicked(new EventHandler<MouseEvent>(){

             public void handle(MouseEvent me)

             {  

                 L3.setText(me.getButton()+ " Button Clicked "+me.getClickCount() + " times.");

             }

        } ) ;


        // Show the stage and its scene.

        myStage.show();

   }

}

Constructor overloading

 

Constructor Overloading 



Constructor in Java

 

A constructor is a special method of a class which is automatically invoked when an object of the class is created.

Constructors

  1. Have the same name of the class
  2. Are always public
  3. Has no return type (not even void)
  4. Generally used for Object Initialization – Set default values, Allocate resources and prepare object state
  5. Cannot be abstract, static or final.
  6. Can be overloaded

Syntax for Creating a Constructor

class <class_name>
{
        // constructor
        <class_name>()
        {
            // code for initializing the object
        }
}

Types of Constructors in Java

Java has three main types of constructors:

  • Default Constructor (No-Argument Constructor) – used to initialize object with default values
  • Parameterized Constructor – Takes arguments to initialize the object
  • Copy constructor – Takes another object of the same class as argument and initializes the new object its values

 


 

Example

// Types of constructors in Java

// Constructor overloading

 

class Rectangle

{

         int l, b;

        

         // Default Constructor

         Rectangle()

         {

                 l = 5;

                 b = 7;

         }

        

         // Parameterized Constructor

         Rectangle(int x, int y)

         {

                 l = x;

                 b = y;

         }

        

         // Copy Constructor

         Rectangle(Rectangle R)

         {

                 this.l = R.l;

                 this.b = R.b;

         }

        

         void fnArea()

         {

                 System.out.println("Area of Rectangle = "+(l*b));

         }

}

 

 

 

class Constructor_Overloading

{

         public static void main(String as[])

         {

                 Rectangle r1 = new Rectangle();

                 System.out.println("Calling Default Constructor.");

                 r1.fnArea();

                

                 Rectangle r2 = new Rectangle(10,20);

                 System.out.println("Calling Parameterized Constructor.");

                 r2.fnArea();

                

                 Rectangle r3 = new Rectangle(r2);

                 System.out.println("Calling Copy Constructor.");

                 r3.fnArea();

         }

}

 

Sample output

 

>javac Constructor_Overloading.java

>java Constructor_Overloading

 

Calling Default Constructor.

Area of Rectangle = 35

Calling Parameterized Constructor.

Area of Rectangle = 200

Calling Copy Constructor.

Area of Rectangle = 200

 

 



Simple Menu Program


Simple Menu Program


// javafx menu


import javafx.application.*;
import javafx.scene.*;
import javafx.stage.*;
import javafx.event.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.scene.control.ScrollPane.*;
import javafx.scene.input.*;
import javafx.scene.text.*;
import javafx.geometry.*;
 
public class Menu_Demo extends Application
{
     public static void main(String []as)
     {
          launch(as);       
     }
     public void init(){}
     public void stop(){}
     public void start(Stage myStage)
     {
myStage.setTitle("JavaFX - Menu");
  
BorderPane bp = new BorderPane();
Label L1 = new Label();
L1.setWrapText(true);
L1.setTextAlignment(TextAlignment.CENTER);
L1.setMaxWidth(150);
// create menubar
MenuBar mb = new MenuBar();
// create menu
Menu m1 = new Menu("_File");
Menu m2 = new Menu("_Edit");
Menu m3 = new Menu("_Help");
        
// create menuitems - File
MenuItem f1 = new MenuItem("New");
MenuItem f2 = new MenuItem("Open");
MenuItem f3 = new MenuItem("Save");
MenuItem f4 = new MenuItem("Close");
MenuItem f5 = new MenuItem("Exit");
// create menuitems - Edit
MenuItem e1 = new MenuItem("Cut");
MenuItem e2 = new MenuItem("Copy");
MenuItem e3 = new MenuItem("Paste");
// create menuitems - Help
MenuItem h1 = new MenuItem("Help");
MenuItem h2 = new MenuItem("About");
// add menuitems to menu
m1.getItems().addAll(f1,f2,f3,f4, new SeparatorMenuItem(), f5);
m2.getItems().addAll(e1,e2,e3);
m3.getItems().addAll(h1, new SeparatorMenuItem(), h2);
        
// add menu to menu bar
mb.getMenus().addAll(m1,m2);
mb.getMenus().add(m3);
         
// place menubar in scene using border layout
bp.setTop(mb);
bp.setCenter(L1);
// Event handling
h2.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent ae)
{
L1.setText("This is a demo program for JavaFX Menu and event handling.");
}
});
f5.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent ae)
{
Platform.exit();
}
});
         
f1.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent ae)
{
L1.setText("File -> New selected");
}
});
f2.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent ae)
{
L1.setText("File -> Open selected");
}
});
Scene myScene = new Scene(bp, 300, 200);
myStage.setScene(myScene);
myStage.show();
}
}

Java File Properties

 

Java File Properties 


// File handling in java

// File Properties


import java.io.*;


class FileProperties

{

public static void main(String as[]) throws IOException

{

File fin = new File("ipt.txt");

if (!fin.exists()) 

System.out.println("\nError: The file does not exist.");

else

{

System.out.println("The file exists.");

System.out.println("File Properties:");

System.out.println("Name: " + fin.getName());

System.out.println("Absolute Path: " + fin.getAbsolutePath());

System.out.println("Is Directory: " + fin.isDirectory());

System.out.println("Is File: " + fin.isFile());

System.out.println("Can Read: " + fin.canRead());

System.out.println("Can Write: " + fin.canWrite());

System.out.println("Can Execute: " + fin.canExecute());

System.out.println("Hidden: " + fin.isHidden());

System.out.println("Size (bytes): " + fin.length());

}

}

}

Generics - Inheritance

 Generics - Inheritannce

Generic Class Hierarchies

Generic classes can be part of a class hierarchy in just the same way as a non-generic class. Thus, a generic class can act as a superclass or be a subclass. The key difference between generic and non-generic hierarchies is that in a generic hierarchy, any type arguments needed by a generic superclass must be passed up the hierarchy by all subclasses. This is similar to the way that constructor arguments must be passed up a hierarchy.

 

Syntax for creating and inheriting generic classes:

 

class super-class-name<type-param-list>

{

    //…

}

class sub-class-name<type-param-list> extends super-class-name<type-param-list>

{

    //…

}

 

// Generic programming

// Inheritance and constructors

// Method overriding

 

class GenA<T1>

{

    public T1 x;

   

    GenA(T1 v1)

    {

         x = v1;

    }

   

    public void fnDisplay()

    {

         System.out.println("x = "+x);

    }

}

 

class GenB<T1> extends GenA<T1>

{

    T1 y;

   

    GenB(T1 v1, T1 v2)

    {

         super(v1);

         y = v2;

    }

   

    public void fnDisplay()

    {

         System.out.println("x = "+x);

         System.out.println("y = "+y);

    }

}

 

public class GenPgm10

{

    public static void main(String as[])

    {  

         GenB<Double> g1 = new GenB<Double>(4.2,5.6);

         g1.fnDisplay();

        

         GenB<String> g2 = new GenB<String>("CSE","IT");

         g2.fnDisplay();

    }

}

 


 

// Generic programming

// Inheritance and constructors

 

class GenA<T1 extends Number>

{

    public T1 l, b;

    double area;

   

    GenA(T1 x, T1 y)

    {

         l = x;

         b = y;

    }

   

    public void fnArea()

    {

         area = l.doubleValue()*b.doubleValue();

         System.out.println("Area = "+area);

    }

}

 

class GenV<T1 extends Number> extends GenA<T1>

{

    T1 h;

    double vol;

   

    GenV(T1 x, T1 y, T1 z)

    {

         super(x, y);

         h = z;

    }

   


 

 

    public <T1 extends Number> void fnVol()

    {

         vol = l.doubleValue()*b.doubleValue()*h.doubleValue();

         System.out.println("Volume = "+vol);

    }

}

 

public class GenPgm9

{

    public static void main(String as[])

    {  

         GenV<Double> g1 = new GenV<Double>(4.2,5.6,6.1);

         g1.fnArea();

         g1.fnVol();

    }

}

 

 


 

// Generic programming

// Find min value in Arrays

 

class Gen<T1 extends Comparable<T1>>

{

    T1 x[];

   

    Gen(T1 []v1)

    {

         x = v1;

    }

   

    public void fnDisplay()

    {

         System.out.println("Array elements");

         for(int i = 0;i<x.length;i++)

             System.out.println(x[i]);

    }

   

    public void fnFind()

    {

         T1 min = x[0];

         for(int i = 1;i<x.length;i++)

             if(x[i].compareTo(min) < 0 )

                 min = x[i];

            

         System.out.println("Minimum value in array = "+min);

    }

}

 

class GenPgm

{

    public static void main(String as[])

    {

         Integer [] ia = {8,4,2,6};

         Gen<Integer> g1 = new Gen<Integer>(ia);

         g1.fnDisplay();

         g1.fnFind();

        

         String []sa = {"cse", "it", "eee", "ece"};

         Gen<String> g2 = new Gen<String>(sa);

         g2.fnDisplay();

         g2.fnFind();

    }

}