用Java实现直接插入排序、性能分析以及适用场景

1.直接插入排序的Java实现:

代码如下:

package mytest;

public class InsertSort {

	public static void getInsertSort(int[] a) {
		if (a == null || a.length == 0) {// 判断数组是否为空
			System.out.println("该数组为空!");
			return;
		}
		int n = a.length;// 将数组的长度赋给n是为了防止每次for循环中判断时都调用length方法影响性能
		int temp;// 放于for循环外面是为了防止重复创建变量
		int j;
		for (int i = 1; i < n; i++) {// 排序的趟数
			temp = a[i];// 赋给temp是为了防止索引i之前的元素向后移动覆盖了索引i的元素
			j = i - 1;
			for (; j >= 0 && a[j] > temp; --j) {// 将大于i位置元素的元素向后移
				a[j + 1] = a[j];
			}
			a[j + 1] = temp;// 找到i应该在的位置,将值放置此处
		}
	}

	public static void main(String[] args) {
		int[] a = { 3, 5, 1, 2, 6, 4, 7, 11, 23, 44, 3, 34 };
		getInsertSort(a);
		System.out.print("直接插入排序:");
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i] + " ");
		}
	}

}

2.直接插入排序的性能分析:

时间复杂度: 
1. 最好情况:O(n) 
2. 平均情况:O(n^2) 
3. 最坏情况:O(n^2) 
空间复杂度:O(1) 
稳定性:稳定(相同元素的相对位置不会改变)

3.适用场景

3.1:当n <= 50时,适合适用直接插入排序和简单选择排序,如果元素包含的内容过大,就不适合直接插入排序,因为直接插入排序需要移动元素的次数比较多.

3.2:当数组基本有序的情况下适合使用直接插入排序和冒泡排序,它们在基本有序的情况下排序的时间复杂度接近O(n).

猜你喜欢

转载自blog.csdn.net/rocling/article/details/81322116