`
lotusyu
  • 浏览: 33630 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类
最新评论

算法导论——插入排序

阅读更多
插入排序好比抓牌,一副牌是待排序的数组,拿一张牌,跟手里的牌从右到左一张张比较,插入到合适的位置。
优点:适应小数据量排序,空间消耗小。
缺点:当数据量比较大时,排序效率不高。

代码结构:
Sort:排序接口
AbstractSort:排序抽象类
InsertSort:排序算法。

Sort:
public interface Sort<T> {
	
	/**
	 * 返回排序后的数组
	 * @return
	 */
	public T[] sort(T[] array);
	
	public T[] sort();
	
}


AbstractSort:
import java.util.Arrays;
import java.util.Comparator;

public abstract class AbstractSort<T> implements Sort<T> {
	
	/**
	 * 待排序数组
	 */
	protected T[] array;
	
	/**
	 * 用于比较数组元素大小
	 */
	protected Comparator<? super T> comp;
	
	public void init(T[] array,Comparator<? super T> comp){
		this.array = array;
		this.comp = comp;
	}
	
	public void print(){
		System.out.println(Arrays.toString(array));
	}
	
	public void swap(int i ,int j){
		T temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}
	
}


InsertSort:
import java.util.Arrays;
import java.util.Comparator;

public class InsertSort<T> extends AbstractSort<T> {

	public InsertSort(T[] array, Comparator<? super T> comp) {
		init(array, comp);
	}

	@Override
	public T[] sort() {
		T[] a = array;
		return sort(a);
	}

	@Override
	public T[] sort(T[] array) {
		for (int i = 1; i < array.length; i++) {
			T current = array[i];
			int j = i - 1;
			/*
			 * 如果array[j]前一个元素大于current,将array[j]移到下一个位置
			 */
			for (; j > -1 && comp.compare(current, array[j]) < 0; j--) {
				array[j + 1] = array[j];
			}
			//将current设置到j+1位置
			array[j + 1] = current;
		}
		return array;
	}

	@Override
	public String toString() {
		return "InsertSort";
	}
	
	public static void main(String[] args) {
		Integer[] temp = null;
		temp = new Integer[] { 16, 14, 8, 7, 9, 3, 2, 4, 1 };

		Comparator<Integer> comp = new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				return o1 - o2;
			}
		};
		Sort<Integer> sort = new InsertSort<Integer>(temp, comp);
		Integer[] clone = temp.clone();
		Arrays.sort(clone);
		boolean equals = Arrays.equals(clone, sort.sort());
		assert equals;
		System.out.println(Arrays.toString(temp));
	}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics