Wednesday, February 24, 2016

Sorting Algorithms - Part I

Selection Sorting

Algorithm

for i = 1:n,
    k = i
    for j = i+1:n, if a[j] < a[k], k = j
    → invariant: a[k] smallest of a[i..n]
    swap a[i,k]
    → invariant: a[1..i] in final position
end

Implementation in Java

public static void selectionSorting(int[] arr){  
  for(int i=0;i<arr.length;i++){
   int k =i;
   for(int j=i+1;j<arr.length;j++){
    if(arr[j]<arr[k]){
     k=j;
    }
   }
   int temp=arr[k];
   arr[k]=arr[i];
   arr[i]=temp;
  }  
 }

Properties

  • O(1) extra space
  • O(n2) comparisons
  • O(n) swaps

Usage

This algorithms has O(n2) comparisons property so run time is always quadratic. So selection sort is not an algorithm that we don't want to use.
Interesting property is it minimizes the number of swaps. There for it can be used in sorting where swapping costs  high.

Saturday, February 13, 2016

What is a Java Bean (JB)

There are lot of confusions among people new to Java programming what is a Java Bean. What does that really mean. Is it a different type of class in Java as Enum . I also had all those questions at the beginning. So here i'm writing about what i learn on the way of finding what java bean is.
  • What is a Java Bean
Simple answer for that is Java Bean is also a normal java class. But all java classes are not java beans.
To be a Java Bean classes should have following,
  1. All properties of the class should be private. Getters and setters can be used to get and set the elements.
  2. Class should has a public but no-argument constructor.
  3. Java Serializable interface should be implemented.
So if those things have in a java class we can call it as a Java Bean. So it is a standard 
People use Word java bean to recognize java classes which are built in a predefined way.

  • Could you give me an example
Here is an example java bean

public class Employee implements java.io.Serializable{  

private int id;  
private String name; 
private String address;
private int age;
  
public Employee(){}  
  
public void setId(int id){this.id=id;}  
  
public int getId(){return id;}  
  
public void setName(String name){this.name=name;}  
  
public String getName(){return name;}  

public void setAge(int age){this.age=age;}

public int getAge(){return age;}
  
}  

Look whether this has all the features mentioned above. YES. so this is a java bean

Note: Remember,  we talked about normal java beans. there is whole different thing named EJB (enterprise java bean). names are similar. but don't be mixed with plain java beans and Enterprise java beans.

Optimize you working enviorenment : Single command to create & move to a directory in linux (C Shell, Bash)

Usually move to a directory just after creating is bit of a anxious task specially if the directory name is too long. mkdir long-name-of...