ObjectSortApp.java

// objectSort.java
// demonstrates sorting objects (uses insertion sort)
// to run this program: C>java ObjectSortApp
////////////////////////////////////////////////////////////////
class Person{
String lastName;
String firstName;
int age;
Person(String lastN,String firstN,int ag)
{
lastName = lastN;
firstName = firstN;
age = ag;
}
public void displayPerson()
{
System.out.println(“Lastname: “+lastName+” ,First Name: “+firstName+”
age: “+age+”\n”);
}
public String getLast()
{
return lastName;
}
}// end class Person
class ArrayInOb
{
private Person[] arr; // ref to array a
private int nElements; // number of data items
public ArrayInOb(int max) // constructor
{
arr = new Person[max];
nElements = 0;
}
public void insert(String last, String first, int ag)
{
arr[nElements] = new Person(last,first,ag);
nElements++;
}
public void display() // displays array contents
{
System.out.print(“\n———–The data of array are: ———-\n”);
for(int i=0;i
{
arr[i].displayPerson();
}
}
public void insertionSort()
{
int in,out;
Person tg = new Person(“”,””,0);
for(out=1; out<nElements; out++) // out is dividing line
{
tg.lastName = arr[out].lastName;
tg.firstName = arr[out].firstName;
tg.age = arr[out].age;
for(in=0;in<out;in++)
{
if((arr[in].lastName.compareTo(arr[out].lastName))>0)
{
for(int j = out;j>in;j–)
{
arr[j].lastName = arr[j-1].lastName;
arr[j].firstName = arr[j-1].firstName;
arr[j].age=arr[j-1].age;
}
arr[in].lastName = tg.lastName;
arr[in].firstName = tg.firstName;
arr[in].age = tg.age;
break;
}
}
} // end for
}
} // end class ArrayInOb
class ObjectSortApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
ArrayInOb arr; // reference to array
arr = new ArrayInOb(maxSize); // create the array
arr.insert(“Evans”, “Patty”, 24);
arr.insert(“Smith”, “Doc”, 59);
arr.insert(“Smith”, “Lorraine”, 37);
arr.insert(“Smith”, “Paul”, 37);
arr.insert(“Yee”, “Tom”, 43);
arr.insert(“Hashimoto”, “Sato”, 21);
arr.insert(“Stimson”, “Henry”, 29);
arr.insert(“Velasquez”, “Jose”, 72);
arr.insert(“Vang”, “Minh”, 22);
arr.insert(“Creswell”, “Lucinda”, 18);
System.out.println(“Before sorting:”);
arr.display(); // display items
arr.insertionSort(); // insertion-sort them
System.out.println(“After sorting:”);
arr.display(); // display them again
} // end main()

}

OrderSortApp

Advertisements

2 thoughts on “ObjectSortApp.java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s