1. 程式人生 > >資料結構與演算法分析之----各種常用排序詳解

資料結構與演算法分析之----各種常用排序詳解

package cn.qunye.Sort_排序;
import java.util.ArrayList;
import java.util.List;
/**
 * 合併排序:
 * 	將待排序元素分成大小大致相同的兩個子集合,分別對兩個子集進行合併排序,最終將排好序的子集合併成所要求的排好序的集合
 * 	時間複雜度:O(logn)
 * @author qunye
 * 2016/03/10
 */
class MergeSortClass<T extends Comparable> {
	
	public void MergeSort(List<T> arr,int left,int right){
		List<T> arrSortTemp = new ArrayList<T>();
		if(left < right){	//至少兩個才需要排序
			int middle = (left+right)/2;
			MergeSort(arr, left, middle);			//左邊進行排序
			MergeSort(arr, middle+1, right);		//右邊進行排序
			merge(arr, arrSortTemp,left, middle, right);	//合併到集合arr
			copy(arr, arrSortTemp, left, right);		//複製回集合arr
			arrSortTemp = null;
		}
	}
	
	/**
	 * 	合併
	 */
	public void merge(List<T> a,List<T> b,int left,int middle,int right){
		int l = left,r = middle+1;
		while((l <= middle) && (r <= right)){
			if(a.get(l).compareTo(a.get(r)) <= 0)
				b.add(a.get(l++));
			else
				b.add(a.get(r++));
		}
		if(l <= middle)
			for(;l<=middle;b.add(a.get(l++)));
		if(r <= right)
			for(;r<=right;b.add(a.get(r++)));		
	}
	
	public void copy(List<T> a,List<T> b,int left,int right){
		int index = 0;
		for(int i=left;i<=right;i++){
			a.set(i, b.get(index++));
		}
	}
}
/**
 * 	學生類
 */
 class Student implements Comparable<Object>{
	
	private String stuName;
	private int stuNum;
	
	public Student(String stuName, int stuNum) {
		super();
		this.stuName = stuName;
		this.stuNum = stuNum;
	}
	public String getStuName() {
		return stuName;
	}
	public void setStuName(String stuName) {
		this.stuName = stuName;
	}
	public int getStuNum() {
		return stuNum;
	}
	public void setStuNum(int stuNum) {
		this.stuNum = stuNum;
	}
	
	@Override
	public int compareTo(Object obj) {
		Student stu;
		if(obj instanceof Student)
			stu = (Student)obj;
		else{
			return -1;
		}
		if(this.getStuNum() <= stu.getStuNum())
			return 0;
		return 1;
	}
}
public class MergeSortMain{
	public static void main(String agrs[]){
		
		List<Student> stus = new ArrayList<Student>();
		stus.add(new Student("小a",15));
		stus.add(new Student("小b",18));
		stus.add(new Student("小c",21));
		stus.add(new Student("小d",13));
		stus.add(new Student("小e",17));
		stus.add(new Student("小f",19));
		stus.add(new Student("小g",10));
		stus.add(new Student("小h",16));
		System.out.println("====================合併排序前====================");
		for(Student stu : stus){
			System.out.println(stu.getStuNum()+":"+stu.getStuName());
		}
		
		new MergeSortClass().MergeSort(stus, 0, stus.size()-1);
		System.out.println("====================合併排序後====================");
		for(Student stu : stus){
			System.out.println(stu.getStuNum()+":"+stu.getStuName());
		}
	}
}

6.改進的合併排序