排序算法Java實現(直接插入排序)


算法描述:對於給定的一個數組,初始時假設第一個記錄自成一個有序序列,其余記錄為無序序列。接着從第二個記錄開始,按照記錄的大小依次將當前處理的記錄插入到其之前的有序序列中,直至最后一個記錄插入到有序序列中為止。
package sorting;

/**
 * 插入排序 
 * 平均O(n^2),最好O(n),最壞O(n^2);空間復雜度O(1);穩定;簡單
 * @author zeng
 *
 */
public class InsertionSort {

	public static void insertionSort(int[] a) {
		int tmp;
		for (int i = 1; i < a.length; i++) {
			for (int j = i; j > 0; j--) {
				if (a[j] < a[j - 1]) {
					tmp = a[j - 1];
					a[j - 1] = a[j];
					a[j] = tmp;
				}
			}
		}
	}

	public static void main(String[] args) {
		int[] a = { 49, 38, 65, 97, 76, 13, 27, 50 };
		insertionSort(a);
		for (int i : a)
			System.out.print(i + " ");
	}
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM