在<<thinking in java>>中看到一段拍案叫绝的代码!起名叫:会排序的Vector
代码如下:
- import java.util.*;
- interface Compare {
- boolean lessThan(Object lhs, Object rhs);
- boolean lessThanOrEqual(Object lhs, Object rhs);
- }
- ////////////////////////////////////////////////////////////////////
- class SortVector extends Vector {
- private Compare compare; // To hold the callback
- public SortVector(Compare comp) {
- compare = comp;
- }
- public void sort() {
- quickSort(0, size() - 1);
- }
- // 快速排序
- private void quickSort(int left, int right) {
- if(right > left) {
- Object o1 = elementAt(right);
- int i = left - 1;
- int j = right;
- while(true) {
- while(compare.lessThan(
- elementAt(++i), o1));
- while(j > 0)
- if(compare.lessThanOrEqual(elementAt(--j), o1))
- break; // out of while
- if(i >= j) break;
- swap(i, j);
- }
- swap(i , right);
- quickSort(left, i-1);
- quickSort(i+1, right);
- }
- }
- //交换位置
- private void swap(int loc1, int loc2) {
- Object tmp = elementAt(loc1);
- setElementAt(elementAt(loc2), loc1);
- setElementAt(tmp, loc2);
- }
- }
- ////////////////////////////////////////////////////////////////////
- public class StringSortTest {
- // 自定义比较规则
- static class StringCompare implements Compare {
- public boolean lessThan(Object l, Object r) {
- return ((String)l).toLowerCase().compareTo(
- ((String)r).toLowerCase()) < 0;
- }
- public boolean
- lessThanOrEqual(Object l, Object r) {
- return ((String)l).toLowerCase().compareTo(
- ((String)r).toLowerCase()) <= 0;
- }
- }
- public static void main(String[] args) {
- SortVector sv =
- new SortVector(new StringCompare());
- // 添加Element
- sv.addElement("d");
- sv.addElement("A");
- sv.addElement("C");
- sv.addElement("c");
- // 排序
- sv.sort();
- Enumeration e = sv.elements();
- // 输出结果
- while(e.hasMoreElements())
- System.out.println(e.nextElement());
- }
- }