Java Data Structures - Contents
A D V E R T I S E M E N T
We've learned about the structure of vectors, lists,
queues, etc., but what if you need some order in the way data is arranged? You have
several options to this; you can simply implement a sort method inside the data storage
class, or you can make the class itself a priority one.
Priority classes are widely used in programs because
they simplify a lot of things. For example, you don't have to worry about sorting data,
the class itself does it for you. Imagine a simulation of a real world queue at a doctor's
office, where people with life threatening injuries get priority over everyone else. The
queue has to accept all people, and sort them according to the seriousness of their
illness; with most serious ending up seeing the doctor first.
The priority concept can be applied anywhere, not
just to queues. It can easily be extended to lists, and vectors. In this section, we will
talk about creating a priority vector (since it's fairly simple). We will also cover some "well
known" sorting algorithms.
How simple is it? The answer is: very! All we need
is to extend the java.util.Vector class, add one insert function, and we are
done. And here's the source:
import java.lang.Comparable;
public class pPriorityVector extends java.util.Vector{
public void pAddElement(Comparable o){
int i,j = size();
for(i=0;i<j&&(((Comparable)(elementAt(i))).compareTo(o)<0);i++);
insertElementAt(o,i);
}
}
As you can see, it's VERY simple. We simply use this
class the way we would use any other java.util.Vector , accept, when we use pAddElement(Comparable)
method, we are inserting in accenting order. We could have just as well written a
descending order one; I think you get the picture...
Lets test this class, and see if it really works.
import java.io.*;
import java.util.*;
import pPriorityVector;
class pPriorityVectorTest{
public static void main(String[] args){
pPriorityVector v = new pPriorityVector();
System.out.print("starting...\nadding:");
for(int i=0;i<10;i++){
Integer j = new Integer((int)(Math.random()*100));
v.pAddElement(j);
System.out.print(" " + j);
}
System.out.print("\nprinting:");
Enumeration enum = v.elements();
while(enum.hasMoreElements())
System.out.print(" "+(Integer)enum.nextElement());
System.out.println("\nDone ;-)");
}
}
The above test program simply inserts ten random java.lang.Integer
objects, and then prints them out. If our class works, the output should produce a sorted
list of number. Our prediction is correct, the output follows.
starting...
adding: 95 85 62 16 39 73 84 43 77 61
printing: 16 39 43 61 62 73 77 84 85 95
Done ;-)
As you can see, we are inserting numbers in an
unsorted order, and get a sorted list when we finally print them out. The technique
illustrated above sorts the numbers upon insertion, some algorithms do sorting when
retrieving data.
Back to Table of Contents
A D V E R T I S E M E N T
|
Subscribe to SourceCodesWorld - Techies Talk |
|