`
AmwuYYGY
  • 浏览: 26643 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

几种排序算法

    博客分类:
  • JAVA
 
阅读更多
public class App {

	public static void main(String[] args) {
		
		int[] data = { 1, 3, 2, 9, 5, 10, 23 };
		
		System.out.println("from:"+Arrays.toString(data));
		
		List<Sort> sortList = new ArrayList<Sort>();
		sortList.add(new InsertionSort());
		sortList.add(new SelectionSort());
		sortList.add(new InsertionSort());
		
		for (Sort sort : sortList) {
			data = sort.sort(data);
			System.out.println(sort.getClass().getSimpleName() + ":"+ Arrays.toString(data));
		}
		

	}

}


from:[1, 3, 2, 9, 5, 10, 23]
InsertionSort:[1, 2, 3, 5, 9, 10, 23]
SelectionSort:[1, 2, 3, 5, 9, 10, 23]
InsertionSort:[1, 2, 3, 5, 9, 10, 23]


package com.tempus.px;

/*

 -------------------插入排序算法--------------------
 从第一个位子开始,后面的数字插入到前面的一个适当的位置

 */
public class InsertionSort implements Sort {

	public int[] sort(int[] data) {
		
		if (data != null) {
			
			for (int i = 1; i < data.length; i++) {
				int temp = data[i];
				int j = i;

				while (data[j - 1] > temp && j>0) {
					data[j] = data[j - 1];// 大数往后移一个位子
					j--;
					
				}
				data[j] = temp;
			}
		}
		return data;
	}

}





package com.tempus.px;



/*
------------------选择排序算法--------------------
与冒泡法排序很相似,从第一个位子开始,与后面的比较取最小,
每次比较记录最小值的位置,最后将最小值的位置的数与当前位置的数对换,只对换一次
*/


public class SelectionSort implements Sort {

	
	public  int[] sort(int[] data){
		
		if(data!=null){
			int min;
			int minLocal;
			for(int i=0;i<data.length;i++){
				min=data[i];
				minLocal=i;
				for(int j =i+1;j<data.length;j++){
					if(min>data[j]){
						minLocal=j;
						min=data[j];
					}
				}
				
				if(minLocal!=i){
					int tmp=data[i];
					data[i]=data[minLocal];
					data[minLocal]=tmp;
				}
			}
		}
		return data;
	}

}



package com.tempus.px;

/*

 -------------------插入排序算法--------------------
 从第一个位子开始,后面的数字插入到前面的一个适当的位置

 */
public class InsertionSort implements Sort {

	public int[] sort(int[] data) {
		
		if (data != null) {
			
			for (int i = 1; i < data.length; i++) {
				int temp = data[i];
				int j = i;

				while (data[j - 1] > temp && j>0) {
					data[j] = data[j - 1];//在数往后移一个位子
					j--;
					
				}
				data[j] = temp;
			}
		}
		return data;
	}

}



http://blog.csdn.net/fenglibing/article/details/1756473
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics