Sort numbers in Javascript array

4 Comments

numbers Sort numbers in Javascript array
Sorting an array in Javascript is a snap.
You create an array and then call sort() method on that array. The Javascript sort() method sorts an array in lexicographical order. This method is very useful in sorting alphanumeric values of an array.

However, sort() will not work if the array consists of numeric values. Because the alphabetical order of numbers is different from their numeric order the sorted array may not be in the order you are expecting. For example, in a dictionary sort the number “11″ would come before number “5″. This may not be the result that you are looking for.
Here is an example

var ages = new Array (23,6,2,16,48,9,6);
ages.sort();

The array will become (16,2,23,48,6,6,9)

Fortunately, the work around for this problem is quite simple.
More

article clipper vert Sort numbers in Javascript array
 

Automatically Sort Vector Elements

1 Comment

Vector class in java.util package is very easy to use. You can add objects of any type in a vector.

You don’t have to worry about declaring the size of the vector. You can just keep adding elements to your object and the vector will dynamically adjust the size. The vector will add elements one after other and will keep them in the order in which your insert them. It means that the elements in the vector are not sorted. Sometimes you need to sort elements in a vector. The Vector class does not offer any sorting mechanism. I created a subclass to sort elements in a vector.
It works with any class that implements Comparable interface or has a Compartor method. If you want elements of your own class sorted in a vector you will need to either make your class implement Comparable or create a Comparator method.


public class SortedVector extends Vector{
public SortedVector(){
super();
}
public void addElement(Object o){
super.addElement(o);
Collections.sort(this);
}
}

Here is a sample program showing how to use this class.

public static void main(String args[]){
SortedVector v =new SortedVector();
v.addElement(new Double(12));
v.addElement(new Double(320));
v.addElement(new Double(21));
System.out.println(v);
}

The output from this program is [12.0, 21.0, 320.0].

article clipper vert Automatically Sort Vector Elements