public class TwoSort {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int keys[] = { 10, 7, 9, 8, 1, 3, 5, 6, 4, 2 };
int temp[] = new int[10];
int arr_size = 10;
bidir_insert(keys, temp, arr_size);
for (int i = 0; i < 10; i++) {
System.out.print(keys[i] + " ");
}
}
public static void bidir_insert(int keys[], int temp[], int arr_size) {
int i, first, last = first = 0;
temp[0] = keys[0]; /* 将第一个元素放入辅助数组 */
/* 利用辅助数组 temp 进行二路插入排序 */
for (i = 1; i < arr_size; ++i) {
if (temp[last] <= keys[i]) {
temp[++last] = keys[i];
} else if (keys[i] <= temp[first]) {
first = (first - 1 + arr_size) % arr_size;
temp[first] = keys[i];
} else {
int index;
for (index = (last - 1 + arr_size) % arr_size;; index = (index - 1 + arr_size)
% arr_size) {
if (temp[index] <= keys[i]) {
int mid = last++;
/* 元素后移 */
while (mid != index) {
temp[(mid + 1) % arr_size] = temp[mid];
mid = (mid - 1 + arr_size) % arr_size;
}
temp[(index + 1) % arr_size] = keys[i];
break;
}
}
}
}
/* 将 temp 的内容按顺序复制到 keys 中 */
for (i = 0; i < arr_size; ++i) {
keys[i] = temp[first];
first = (first + 1) % arr_size;
}
}
}
2路插入排序
最新推荐文章于 2023-05-06 00:59:43 发布