1 23 24 29 30 package com.sun.enterprise.tools.common; 31 32 37 39 import java.util.*; 40 41 public class Sorter 42 { 43 44 46 public static void sort(Vector v) 47 { 48 if(v.size() <= 1) 49 return; 50 51 SorterObject[] arr = new SorterObject[v.size()]; 52 Enumeration e = v.elements(); 53 54 for(int i = 0 ; e.hasMoreElements() ; i++) 55 { 56 arr[i] = new SorterObject(e.nextElement()); 57 } 58 59 mergeSort(arr); 60 61 v.removeAllElements(); 62 63 for(int i = 0; i < arr.length; i++) 64 { 65 v.addElement(arr[i].obj); 66 } 67 } 68 69 71 private static void mergeSort(SorterObject[] arr) 72 { 73 int low = 0; 74 int high = arr.length; 75 76 for (int i = low; i < high; i++) 77 { 78 for (int j = i; j > low && arr[j-1].sortName.compareTo(arr[j].sortName) > 0; j--) 79 { 80 swap(arr, j, j-1); 81 } 82 } 83 } 84 85 87 private static void swap(SorterObject x[], int a, int b) 88 { 89 SorterObject t = x[a]; 90 x[a] = x[b]; 91 x[b] = t; 92 } 93 94 96 private static void print(Vector v, String s) 97 { 98 System.out.println(s + "\n"); 100 for(Enumeration e = v.elements(); e.hasMoreElements(); ) 101 { 102 System.out.println("" + e.nextElement()); } 104 } 105 106 108 public static void main(String [] args) 109 { 110 Vector v1 = new Vector(); 111 114 v1.addElement("aaaa"); v1.addElement("zzzz"); v1.addElement("dddd"); v1.addElement("ccccx"); v1.addElement("cccc"); v1.addElement("cccc"); v1.addElement("cccc"); v1.addElement("bbbb"); 123 print(v1, "****** before"); sort(v1); 125 print(v1, "\n******after"); } 127 128 } 130 131 133 class SorterObject 134 { 135 SorterObject(Object obj) 136 { 137 this.obj = obj; 138 sortName = obj.toString(); 139 } 140 String sortName; 141 Object obj; 142 } 143 | Popular Tags |