JAVA 泛型练习
二分查找:
public class Q212 { public static void main(String [] args) { Integer []arr = {1,2,3,4,5,6,7,8};//Integer型比较 System.out.println(Q212.<Integer>Erfen(arr, 5)); String []arr1 = {"a","b","c","d","e","f","g"};//String型比较 System.out.println(Q212.<String>Erfen(arr1, "d")); Double []arr2 = {3.1,4.3,5.4,6.5,7.3,8.1,9.2,10.7};//Double型比较 System.out.println(Q212.<Double>Erfen(arr2, 9.2)); } public static <E extends Comparable<E>> int Erfen(E []list,E index) { int first = 0; int last = list.length - 1; int mid; while(first<=last) { mid = first + (last - first)/2; if(list[mid].compareTo(index) == 0) return mid; if(list[mid].compareTo(index) < 0) first = mid + 1; if(list[mid].compareTo(index) > 0) last = mid - 1; } return -1; } }
选择排序:
public class Q213 { public static void main(String []args) { Integer []arr = {5,4,1,6,2}; Q213.<Integer>selectionSort(arr); for(int i = 0;i < arr.length; i++) System.out.print(arr[i]+" "); } public static <E extends Comparable<E>> void selectionSort(E []list) { int i,j; for(i = 0;i < list.length-1; i++/*,System.out.println("nihao")*/) for(j = i+1;j < list.length; j++) if(list[j].compareTo(list[i]) < 0) //swap(list[i],list[j]); { //System.out.println(list[i]+" "+list[j]); E m = list[i]; list[i] = list[j]; list[j] = m; } //for(i = 0;i < list.length; i++) //System.out.print(list[i]+" "); } /* public static <E>void swap(E x,E y) { E m; m = x; x = y; y = m; }*/ }
插入排序:
public class Q214 { public static void main(String []args) { Integer []arr = {2,3,6,1,8,3}; Q214.<Integer>insertionSort(arr); for(int i=0;i<arr.length;i++) { System.out.print(arr[i]+" "); } } public static <E extends Comparable<E>> void insertionSort(E []list) { int i,j; for(i = 1;i<list.length;i++) for(j=0;j<i;j++) if(list[i].compareTo(list[j])<0) { E m = list[i]; for(int p = i-1; p>=0; p--) list[i--] = list[p]; list[i] = m; } } }