查找与排序 In Java

直接记录一段代码

package searchandsort;


public class SortingAndSearch<T extends Comparable<T>> {

	/**
	 * 线性查找
	 * @param data 数组对象 
	 * @param min 起始索引
	 * @param max 结束索引
	 * @param target 查找目标
	 * @return 是否查找到
	 */
	public  boolean linearSearch(T[] data, int min, int max, T target) {
		
		int index = min;;
		boolean found = false;
		while (!found && index <= max) {
			
			if (data[index].compareTo(target) == 0) {
				found = true;
				break;
			}
			index++;
		}
		
		return found;
	}
	
	//二分查找
	public  boolean binarySearch(T[] data, int min, int max, T target) {
		boolean found = false;
		int mid = (max + min) / 2; //中间
		if (data[mid].compareTo(target) == 0) { //找到了
			found = true;
		} else if (data[mid].compareTo(target) > 0) {
			if (min <= mid - 1) {
				found = binarySearch(data, min, mid-1, target); //左边递归
			}
		} else {
			if (mid + 1 <= max) {
				found = binarySearch(data, mid+1, max, target); //左边递归
			}
		}
		//1  4  1 1
		return found;
	}
	
	//选择排序
	public void selectionSort(T[] data) {
		int min, len = data.length;
		T temp;
		for (int index = 0; index < len - 1; index++) {
			min = index;
			for (int scan = index + 1; scan < len; scan++) {
				if (data[scan].compareTo(data[min]) < 0) {
					min = scan;
				}
			}
			if (index != min) {
				temp = data[min];
				data[min] = data[index];
				data[index] = temp;
			}
		}
	}
	
	static class Contact implements Comparable<Contact> {
		public String firstName, lastName;
		public Contact(String firstName, String lastName) {
			super();
			this.firstName = firstName;
			this.lastName = lastName;
		}

		@Override
		public int compareTo(Contact o) {
			int res; 
			if (lastName.equals(o.lastName)) {
				res = firstName.compareTo(o.firstName);
			} else {
				res = lastName.compareTo(o.lastName);
			}
			return res;
		}

		@Override
		public String toString() {
			return "Contact [firstName=" + firstName + ", lastName=" + lastName
					+ "]";
		}
		
	}
}


你可能感兴趣的:(排序,二分查找,查找,选择排序)