排序算法之插入排序
插入排序(Insert Sort)
插入排序核心思想是其主要的实现思想是将数据按照一定的顺序一个一个的插入到有序的表中.
算法描述
(1)初始状态,无序序列R[1...n]
(2)新建一个有序序列,每次从无序序列中拿一个数放到有序序列中,放进去之后,依然是有序序列
代码实现
public class InsertSort {
public static void main(String[] args) {
int[] num = new int[]{3,2,4,1,5,7,6};
num = sort2(num);
for (int k : num) {
System.out.print(k + " ");
}
}
public static int[] sort(int[] num){
for (int i = 1; i < num.length; i++){
int temp = i;
for (int j = i-1; j >= 0; j--){
if(num[temp] > num[j]){
break;
}else{
int tempNum = num[temp];
num[temp] = num[j];
temp = j;
num[j] = tempNum;
}
}
}
看了一些网上的算法实现,发现我的实现有一个地方很多余,就是比较完之后,只需要将大的往后移,但是当前的数不用和大数交换,而是留着一个位置出来,等比较往一次再进行赋值。
优化
public static int[] improve_sort(int[] num){
for(int index = 1; index<num.length; index++){//外层向右的index,即作为比较对象的数据的index
int temp = num[index];//用作比较的数据
int leftindex = index-1;
while(leftindex>=0 && num[leftindex]>temp){//当比到最左边或者遇到比temp小的数据时,结束循环
num[leftindex+1] = num[leftindex];
leftindex--;
}
num[leftindex+1] = temp;//把temp放到空位上
}
return num;
}
算法分析
最佳情况:T(n) = O(n) 最坏情况:T(n) = O(n2) 平均情况:T(n) = O(n2)
不负光阴不负卿