秩序配列の集計
3243 ワード
import java.util.Arrays;
public class Sort {
public static void main(String[] args) {
//
int[] array1 = { 3, 6, 12, 22, 33, 34, 65, 88 };
int[] array2 = { 1, 2, 3, 4, 6, 7, 8, 9, 10 };
//
int[] array3 = { 45, 44, 33, 8, 5, 3, 2, 1 };
int[] array4 = { 76, 45, 34, 23, 10, 3, 1 };
// ,
System.out.println(Arrays.toString(sort(array1, array2)));
// ,
System.out.println(Arrays.toString(sort(array1, array3)));
// ,
System.out.println(Arrays.toString(sort(array4, array2)));
// ,
System.out.println(Arrays.toString(sort(array3, array4)));
}
private static int[] sort(int[] array1, int[] array2) {
//
if (null == array1 || array1.length == 0) {
return array2;
}
if (null == array2 || array2.length == 0) {
return array1;
}
int len1 = array1.length;
int len2 = array2.length;
int[] result = new int[len1 + len2];
// 0 : 1 :
int flag1 = array1[0] < array1[len1 - 1] ? 0 : 1;
int flag2 = array2[0] < array2[len2 - 1] ? 0 : 1;
//
if (flag1 == 0 && flag2 == 0) {
int i = 0, j = 0, k = 0;
while (i < len1 && j < len2) {
if (array1[i] < array2[j]) {
result[k++] = array1[i++];
} else {
result[k++] = array2[j++];
}
}
while (i < len1) {
result[k++] = array1[i++];
}
while (j < len2) {
result[k++] = array2[j++];
}
// array1 array2
} else if (flag1 == 0 && flag2 == 1) {
int i = 0, j = len2 - 1, k = 0;
while (i < len1 && j >= 0) {
if (array1[i] < array2[j]) {
result[k++] = array1[i++];
} else {
result[k++] = array2[j--];
}
}
while (i < len1) {
result[k++] = array1[i++];
}
while (j >= 0) {
result[k++] = array2[j--];
}
// array1 array2
} else if (flag1 == 1 && flag2 == 0) {
int i = len1 - 1, j = 0, k = len1 + len2 - 1;
while (i >= 0 && j < len2) {
if (array1[i] < array2[j]) {
result[k--] = array1[i--];
} else {
result[k--] = array2[j++];
}
}
while (i >= 0) {
result[k--] = array1[i--];
}
while (j < len2) {
result[k--] = array2[j++];
}
//
} else if (flag1 == 1 && flag2 == 1) {
int i = len1 - 1, j = len2 - 1, k = len1 + len2 - 1;
while (i >= 0 && j >= 0) {
if (array1[i] < array2[j]) {
result[k--] = array1[i--];
} else {
result[k--] = array2[j--];
}
}
while (i >= 0) {
result[k--] = array1[i--];
}
while (j >= 0) {
result[k--] = array2[j--];
}
}
return result;
}
}