Sorting Objects:
For simplicity we have applied the sorting on the primitive data type.However,sorting routines will more likely be applied to objects than primitive types.
Simple Demonstration:
/**
*
*/
/**
* @author Abhinaw.Tripathi
*
*/
class Person
{
private String lastName;
private String firstName;
private int age;
public Person(String fName,String lName,int age)
{
this.lastName=lName;
this.age=age;
this.firstName=fName;
}
public void displayPerSon()
{
System.out.println("Last Name: " + lastName);
System.out.println("First Name: " + firstName);
System.out.println("Age: " + age);
}
public String getLast()
{
return lastName;
}
}
class ArrayInObject
{
private Person[] a;
private int nElems;
public ArrayInObject(int max)
{
a=new Person[max];
nElems=0;
}
public void insert(String last,String first,int age)
{
a[nElems]=new Person(last, first, age);
nElems++;
}
public void display()
{
for(int k=0;k<nElems;k++)
a[k].displayPerSon();
System.out.println(" ");
}
public void insertionSort()
{
for(int i=0;i<nElems;i++)
{
int in,out;
for(out=1;out<nElems;out++)
{
Person temp=a[out];
in=out;
while(in> 0 && a[in-1].getLast().compareTo(temp.getLast()) > 0)
{
a[in]=a[in-1];
--in;
}
a[in]=temp;
}
}
}
}
public class ObjectSortApp {
/**
*
*/
public ObjectSortApp() {
// TODO Auto-generated constructor stub
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayInObject arr=new ArrayInObject(100);
arr.insert("tripathi", "abhinaw", 27);
arr.insert("pokhariyal", "sandeep", 26);
arr.insert("mishra", "anand", 30);
arr.insert("singh", "brijesh", 35);
arr.insert("punwani", "manish", 40);
arr.display();
System.out.println("Before Sorting....");
arr.insertionSort();
System.out.println("After Sorting......");
arr.display();
}
}
Comparing the Simple Sorts:
The selection sort minimizes the number of swaps,but the number of comparisons is still high.This sort might be useful when the amount of data is small or the data is almost sorted.For larger amounts of data,quick sort is generally considered the fastest approach.