所以我有这个数组,必须使用Insionsionssort:
( 4 1 2 3 )= arr[0] ,
( 1 2 3 4 )=arr[1] ,
( 4 3 2 1 ) = arr[2],
( 3 1 2 4 )= arr[3] ,
( 4 3 1 2 ) = arr[4] ,
( 2 1 3 4 ) = arr[5] ,
( 4 1 3 2 ) = arr[6] ,
( 1 4 2 3 )= arr[7]
如果数组1的值1-4与数组2的值1-4之间的差较大,则一个数组将与另一个数组交换。例如:arr [0]
所以排序后的数组将如下所示:
(3,1,2,4) < (4,1,2,3) < (1,4,2,3) < (2,1,3,4) < (4,1,3,2) < (4,3,1,2) < (1,2,3,4) < (4,3,2,1)
我有此方法的atm,仅在其中检查了第一个条件:
public int insertionsort(permutation[] arr, int gap) {
int count = 0;
for (int i = gap; i<arr.length-1; i++) {
count++;
permutation new = arr[i];
int k = i;
System.out.println("K: " + k);
System.out.println("gap: "+ gap);
while(Math.abs(arr[i].value(1)-arr[i].value(4)) > Math.abs(arr[i-gap].value(1) -
arr[i-gap].value(4))) {
arr[k] = arr[k-gap];
k = k-gap;
System.out.println("k-gap: " + (k-gap));
}
arr[k] = new;
}
return count;
}
现在,我认为我的数组将首先按照小差异的顺序进行排序,但这似乎并不正确。希望你能帮助我!
gap
参数的目的是什么,希望您可以在需要时将其合并,但这是将标准Insertion Sort方法直接翻译成Java。static void sort(permutation[] perms)
{
for(int i=1; i<perms.length; i++)
{
permutation fixed = perms[i];
int j = i - 1;
while(j >= 0 && perms[j].compareTo(fixed) > 0)
{
perms[j+1] = perms[j];
j -= 1;
}
perms[j+1] = fixed;
}
}
猜测permutation
类的外观:
static class permutation { int len; int[] arr; public permutation(int... vals) { len = vals.length; arr = vals.clone(); } int value(int pos) { return arr[pos-1]; } public int compareTo(permutation p) { int cmp = Math.abs(value(1)-value(len)) - Math.abs(p.value(1)-p.value(len)); if(cmp == 0) for(int i=1; cmp==0 && i<=len; i++) cmp = value(i)-p.value(i); return cmp; } }
测试:
permutation[] perms = { new permutation(4,1,2,3), new permutation(1,2,3,4), new permutation(4,3,2,1), new permutation(3,1,2,4), new permutation(4,3,1,2), new permutation(2,1,3,4), new permutation(4,1,3,2), new permutation(1,4,3,2) }; sort(perms); for(permutation p : perms) System.out.println(Arrays.toString(p.arr));
输出:
[1, 4, 3, 2] [3, 1, 2, 4] [4, 1, 2, 3] [2, 1, 3, 4] [4, 1, 3, 2] [4, 3, 1, 2] [1, 2, 3, 4] [4, 3, 2, 1]