package insert;
/*
* 二路插入排序算法
* 利用新的数组b[]来暂时存储对原数组a[]操作后的结果
* 首先将a[0]赋值给b[0]
* 从i=1,开始至i<length,遍历length-1次,每次处理a[i],看将其放到b[]中什么位置
* 首先判断,如果a[i]大于a[0],则将其放到b[0]之后(需要按照插入排序放,将b[0]后的数组看成递增数组)
* 如果a[i]小于a[0],则将其放到b[0]之前,在这里为了节省空间,也便于操作,我们利用循环数组原理,将数组最后的几个设置为b[0]的前面
* (同样按照插入排序放,将b[0]之前的数组看成递增数组
*/
public class TwoLuInsert {
public static void print(int[] arr){
for(int n=0;n<arr.length;n++){
System.out.print(arr[n]+" ");
}
System.out.println();
}
static void fun(int[] a){
int length = a.length;
int[] b = new int[length];
b[0] = a[0];
int first = 0;//头指针
int finals = 0;//尾指针
System.out.print(1+"次 ");
print(b);
for(int i=1;i<length;i++){
if(a[i]>=b[0]){
int j;
for(j=finals;j>=0 && a[i]<b[j];j--){
b[j+1] = b[j];
}
b[j+1] = a[i];
System.out.print(i+1+"次 ");
print(b);
finals++;
continue;
}else{
if(first==0){
first =length-1;
}
int j;
for(j=first;j<length && a[i]>b[j];j++){
b[j-1] = b[j];
}
b[j-1] = a[i];
System.out.print(i+1+"次 ");
print(b);
first--;
continue;
}
}
}
public static void main(String[] args) {
int[] arr = {49,38,65,97,76,13,27,49};
fun(arr);
}
}
/*
* 二路插入排序算法
* 利用新的数组b[]来暂时存储对原数组a[]操作后的结果
* 首先将a[0]赋值给b[0]
* 从i=1,开始至i<length,遍历length-1次,每次处理a[i],看将其放到b[]中什么位置
* 首先判断,如果a[i]大于a[0],则将其放到b[0]之后(需要按照插入排序放,将b[0]后的数组看成递增数组)
* 如果a[i]小于a[0],则将其放到b[0]之前,在这里为了节省空间,也便于操作,我们利用循环数组原理,将数组最后的几个设置为b[0]的前面
* (同样按照插入排序放,将b[0]之前的数组看成递增数组
*/
public class TwoLuInsert {
public static void print(int[] arr){
for(int n=0;n<arr.length;n++){
System.out.print(arr[n]+" ");
}
System.out.println();
}
static void fun(int[] a){
int length = a.length;
int[] b = new int[length];
b[0] = a[0];
int first = 0;//头指针
int finals = 0;//尾指针
System.out.print(1+"次 ");
print(b);
for(int i=1;i<length;i++){
if(a[i]>=b[0]){
int j;
for(j=finals;j>=0 && a[i]<b[j];j--){
b[j+1] = b[j];
}
b[j+1] = a[i];
System.out.print(i+1+"次 ");
print(b);
finals++;
continue;
}else{
if(first==0){
first =length-1;
}
int j;
for(j=first;j<length && a[i]>b[j];j++){
b[j-1] = b[j];
}
b[j-1] = a[i];
System.out.print(i+1+"次 ");
print(b);
first--;
continue;
}
}
}
public static void main(String[] args) {
int[] arr = {49,38,65,97,76,13,27,49};
fun(arr);
}
}