1. 程式人生 > >java實現三種簡單排序以及改良:氣泡排序,選擇排序,直接插入排序

java實現三種簡單排序以及改良:氣泡排序,選擇排序,直接插入排序

import java.util.Arrays;


public class Sort {
	public static void main(String[] args) {
		int[] array={18,17,20,9,10};
		bubble1(array);
		System.out.println(Arrays.toString(array));
		
	}
	//氣泡排序:從第一個數開始,將最大的數移到最前面,重複
	//簡單的改進(有多種改進方式)某一趟沒有任何資料交換,資料排序完畢
	public static void bubble1(int[] array){
		int temp = 0;
		boolean issorted = false;
		for (int i = array.length-1; i >0&&!issorted ; i--) {
			issorted = true;
			for (int j = 0; j <i; j++) {
				if(array[j]>array[j+1]){
				issorted = false ;
				temp = array[j];
				array[j] = array[j+1];
				array[j+1] = temp;
				}
			}
		}
	}
	//氣泡排序:從最後一個數數開始,將最小的數移到最前面,重複
	public static void bubble2(int[] array){
		int temp = 0;
		for (int i = 0; i < array.length-1; i++) {
			for (int j = array.length-1; j >i; j--) {
				if(array[j]<array[j-1]){
					temp = array[j];
					array[j] = array[j-1];
					array[j-1] = temp;
				}
			}
		}
	}
	//選擇排序
	public static void selection(int[] array){
		int k = 0,temp = 0;
		for (int i = 0; i < array.length-1; i++) {//比較到倒數第二個,最後一個自然放置好
			k=i;
			for (int j = 0; j < array.length; j++) {//因為有k=i,故從i+1開始1 17 20 9 10
				if (array[k]>array[j]) {
					k=j;
				}
			}
			if(k!=i){	
			temp = array[i];
			array[i] = array[k];
			array[k] = temp;
			}
		}
	}
	//插入排序
	public static void insert(int[] array){
		int temp;
		int j;
		for (int i = 1; i < array.length; i++) {
			temp = array[i];
			for(j = i-1; j >= 0&&array[j] > temp; j--) {//前面數值大於temp才後移
				    //如果這裡新增if(array[j]>temp) 
					array[j+1] = array[j];					
			}
			array[j+1] = temp;
		}
	}
	
}