您的位置:首页 > 其它

插入排序

2016-02-02 18:03 267 查看
1、直接插入排序

package xz.learn.agorithm.insertSort;

public class StraightInsertionSort {
public static void main(String[] args) {
int[] array={1,2,34,5,12,445,32,31,53,32,-12};
straightInsertionSort(array);
}
public static void straightInsertionSort( int[] a){
//a[0]作为独自有序序列,从1开始计算
for (int i = 1; i < a.length; i++) {
if(a[i]<a[i-1]) {
/**
* 从i-1往前遍历并且同时移位
*/
int temp=a[i];
int k=i-1;
for(int j=k;j>0&&temp<a[j];j--) {
a[j+1]=a[j];//右移
k--;
}
a[k+1]=temp;
}
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}


折半插入算法:

在将一个新元素插入已排好序的数组的过程中,寻找插入点时,将待插入区域的首元素设置为a[low],末元素设置为a[high],则轮比较时将待插入元素与a[m],

其中m=(low+high)/2相比较,如果比参考元素小,则选择a[low]到a[m-1]为新的插入区域(即high=m-1),否则选择a[m+1]到a[high]为新的插入区域(即low=m+1),

如此直至low<=high不成立,即将此位置之后所有元素后移一位,并将新元素插入a[high+1]。

package xz.learn.agorithm.insertSort;

public class BinaryInsertSort {
/**
* 折半插入算法
* @param args
*/
public static void main(String[] args) {
int[] array={1,2,34,5,12,445,32,31,53,32,-12};
binaryInsertSort(array);
}
public static void binaryInsertSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int temp=a[i];
int low = 0;
int high = i-1;
while(low<=high){
int m = (low+high)/2;
if(temp<a[m]){
high=m-1;
}else {
low=m+1;
}
}
for(int j = i; j >= low + 1; j--){
a[j] = a[j - 1];
}
a[low] = temp;
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: