package com.cn.hbut.daoImpl;
/**
* @author Administrator
* 直接插入排序
*
*/
public class InsertSort {
//直接插入排序
//{3 2 1 5 6}
//{2 3 1 5 6}
public static void insertSort(int [] arr){
for(int i=1;i<arr.length;i++){
int temp =arr[i];
int j=i-1;
while(j>=0&&arr[j]>temp){
arr[j+1]=arr[j];
j--;
}
arr[j+1]=temp;
}
}
//二次插入排序
//思想:[有序区]-[无序区],把无序区的数加入到有序区,插入是二分插入法寻找点
//{3 2 1 5 6}
//{2 3 1 5 6}
public void secondInertSort(int [] arr){
int i,j,low ,high,mid;
int temp;
for(i=1;i<arr.length;i++){
low=0;
high=i-1;
temp=arr[i];
while(low<=high){
mid=(low+high)/2;
if(arr[mid]>temp){
high=mid-1;
}
if(arr[mid]<temp){
low=mid+1;
}
}
//记录后移
for(j=i-1;j>=high+1;j--){
arr[j+1]=arr[j];
}
arr[high+1]=temp;
}
}
public static void main(String[] args) {
int [] arr ={3,2,1,5,6};
// InsertSort.insertSort(arr);
InsertSort sort = new InsertSort();
sort.secondInertSort(arr);
for(int x:arr){
System.out.print(x+" ");
}
}
}
数据结构之二分插入排序------java实现
最新推荐文章于 2024-08-22 14:19:38 发布