------------------------------------冒泡排序------------------------------------
定义接口:抽象出排序数组中元素的不同状态(可否比较)
public interface SortInter { public <T extends Comparable<T>> void sort(T[] list);//T实例本身就是可以比较的 public <T> void sort(T[] list,Comparator<T> com);//通过自定义比较器比较两个T }
实现接口:具体实现排序方法
public class TestSort implements SortInter { @Override public <T extends Comparable<T>> void sort(T[] list) { boolean swapped = true;//根据上次排序有没有交换判断是否退出外层循环 for (int i = 1,len = list.length; i < len && swapped; i++) { swapped = false; for (int j = 0; j < len - i; j++) {//每一次内层循环的循环次数都较前一次减一 if(list[j].compareTo(list[j+1]) > 0) { T temp ; temp = list[j]; list[j] = list[j+1]; list[j+1] = temp; swapped = true; } } } } @Override public <T> void sort(T[] list, Comparator<T> com) { boolean swapped = true; for (int i = 1,len = list.length; i < len && swapped; i++) { for (int j = 0; j < len - i; j++) { if(com.compare(list[j], list[j+1]) > 0) { T temp ; temp = list[j]; list[j] = list[j+1]; list[j+1] = temp; swapped = true; } } } } public static void main(String[] args) { Integer[] arr = {3,1,23,21,12,2,121,24}; new TestSort().sort(arr); System.out.println(Arrays.toString(arr)); String[] strArr = {"asd","as","Asf","Cbc","cxz","bca"}; Comparator<String> com = new Comparator<String>() { @Override public int compare(String str1, String str2) { return str1.compareTo(str2); } }; new TestSort().sort(strArr,com); for (int i = 0; i < strArr.length; i++) { System.out.println(strArr[i]+" "); } } }
控制台结果:
[1, 2, 3, 12, 21, 23, 24, 121] Asf Cbc as asd bca cxz
------------------------------------折半查找------------------------------------
package com.qf.test1; public class TestSearch { /** * 使用循环实现折半查找 * @param t * @param key * @return */ public static <T extends Comparable<T>> int binarySearch(T[] t , T key) { int low = 0; int high = t.length - 1; int mid ; while(low <= high) { mid = low + (high-low)/2; //不使用(low+high)/2是因为可能low+high的值溢出int范围无法计算;还可以使用右移>>1或者无符号右移>>>1 if(t[mid].compareTo(key) > 0) { high = mid - 1; }else if(t[mid].compareTo(key) < 0){ low = mid + 1; }else { return mid; } } return -1; } /** * 使用递归实现折半查找 * @param t * @param low * @param high * @param key * @return */ public static <T extends Comparable<T>> int binarySearch(T[] t,int low,int high,T key) { if(low <= high) { int mid = low + (high-low)/2; if(t[mid].compareTo(key) > 0) { return binarySearch(t,low,mid-1,key); }else if(t[mid].compareTo(key) < 0) { return binarySearch(t,low,mid-1,key); }else { return mid; } } return -1; } public static void main(String[] args) { Integer[] arr = {1, 2, 3, 12, 21, 23, 24, 121}; System.out.println("index:"+TestSearch.binarySearch(arr, 12)); } }
控制台打印
index:3