Here you can find the source of orderedStringInsert(String key, Vector into)
Parameter | Description |
---|---|
key | The string to insert. |
into | The target sorted vector. |
static void orderedStringInsert(String key, Vector into)
//package com.java2s; import java.util.*; public class Main { /**/*from w w w . j a v a2 s. c om*/ * Insert a String into a vector, maintaing the order. * * @param key The string to insert. * @param into The target sorted vector. */ static void orderedStringInsert(String key, Vector into) { int lo = 0; int hi = into.size() - 1; int idx = -1; String item = null; int cmp = 0; if (hi >= lo) { while ((hi - lo) > 1) { idx = (hi - lo) / 2 + lo; item = (String) into.elementAt(idx); cmp = item.compareToIgnoreCase(key); if (cmp == 0) { return; } else if (cmp < 0) { lo = idx; } else if (cmp > 0) { hi = idx; } } switch (hi - lo) { case 0: item = (String) into.elementAt(hi); if (item.equals(key)) return; idx = (item.compareToIgnoreCase(key) < 0) ? hi + 1 : hi; break; case 1: String loitem = (String) into.elementAt(lo); String hiitem = (String) into.elementAt(hi); if (loitem.equals(key)) return; if (hiitem.equals(key)) return; if (key.compareToIgnoreCase(loitem) < 0) { idx = lo; } else if (key.compareToIgnoreCase(hiitem) < 0) { idx = hi; } else { idx = hi + 1; } break; default: throw new RuntimeException("implementation bug."); } } // Add this key to the vector: if (idx < 0) idx = 0; into.insertElementAt(key, idx); return; } }