Java Vector Sort sortIntegerVector(Vector toSort)

Here you can find the source of sortIntegerVector(Vector toSort)

Description

Sorts an vector.

License

LGPL

Parameter

Parameter Description
toSort the <Integer> Vector to sort

Return

Vector sorted values.

Declaration

@SuppressWarnings({ "rawtypes", "unchecked" })
public static Vector sortIntegerVector(Vector toSort) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.util.*;

public class Main {
    /**//from  w  w  w  . j  a va  2  s. c o m
     * Sorts an <Integer> vector.
     * @param toSort the <Integer> Vector to sort
     * @return Vector<Integer> sorted values.
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Vector sortIntegerVector(Vector toSort) {
        if (toSort == null) {
            return new Vector();
        }
        int size = toSort.size();
        if (size == 0) {
            return toSort;
        }

        Vector sorted = new Vector();

        //Create a String array, since a Vector is not very flexible
        Integer[] elements = new Integer[size];
        for (int i = 0; i < size; i++) {
            //Using the toString method so other Objects coult be sorted as well.
            //This will cause a problem with the returned values (they will be strings!)
            elements[i] = (Integer) toSort.elementAt(i);
        }
        //Sorting the array
        integerQuicksort(elements, 0, size - 1);

        for (int i = 0; i < size; i++) {
            sorted.add(elements[i]);
        }
        return sorted;
    }

    /**
     * A static integer- quicksort method.
     * Was implemented because i wasn't sure if JavaME supports Comparable Objects
     * @param elements - the String[] elements
     * @param low Lowest position in the array
     * @param hi Highest position in the array
     */
    private static void integerQuicksort(Integer[] elements, int low, int hi) {
        int i = low, j = hi;
        Integer temp;

        Integer x = elements[(low + hi) / 2];

        do {
            while (elements[i] - x/*.compareTo(x)*/ < 0) {
                i++;
            }
            while (elements[j] - x > 0) {
                j--;
            }
            if (i <= j) {
                temp = elements[i];
                elements[i] = elements[j];
                elements[j] = temp;
                i++;
                j--;
            }
        } while (i <= j);

        if (low < j) {
            integerQuicksort(elements, low, j);
        }
        if (i < hi) {
            integerQuicksort(elements, i, hi);
        }
    }
}

Related

  1. sort(Vector unsorted, int sortKeyPos, int maxVal)
  2. sortInsert(Vector v, Object obj)