* 思路一
* 1、先合并成一个无序数组
* 2、冒泡排序 这个无序数组
* 思路二
* 1、先把两个数组分别冒泡排序,变成两个有序数组
* 2、再把两个有序数组合并
实现一:
public static void methord01() {
int a[] = {1, 6, 9, 4, 5};
int b[] = {7, 0, 3, 2, 8};
ArrayList<Integer> alist = new ArrayList<Integer>(a.length + b.length);
for (int i = 0; i < a.length; i++) {
alist.add(a[i]);
}
for (int j = 0; j < b.length; j++) {
alist.add(b[j]);
}
int c[] = new int[alist.size()];
for (int i = 0; i < alist.size(); i++) {
c[i] = alist.get(i);
}
bubbleSort(c);
System.out.println("整合后的数组是:");
for (int k = 0; k < c.length; k++) {
System.out.print(c[k]);
}
}
/**
* 冒泡排序
*
* @param array
*/
public static void bubbleSort01(int[] array) {
int temp;
for (int i = 0; i < array.length; i++) {// 趟数
for (int j = 0; j < array.length - i - 1; j++) {// 比较次数
if (array[j] < array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
实现二:
public static int[] methord02() {
int first[] = {1, 6, 9, 4, 5};
int second[] = {7, 0, 3, 2, 8};
//冒泡排序
bubbleSort(first);
bubbleSort(second);
int result[] = new int[first.length + second.length];
//排序后,如果第一个数组的最后一个元素小于第二个数组的第一个元素,则直接合并 first[],second[]
if (first[first.length - 1] <= second[0]) {
// first+second
result = connectArr02(first, second);
return result;
}
//排序后,如果第二个数组的最后一个元素小于第一个数组的第一个元素,则直接合并second[], first[]
if (second[second.length - 1] <= first[0]) {
// second+first
result = connectArr02(second, first);
return result;
}
int firstIndex = 0;
int secondIndex = 0;
int resultIndex = 0;
while (firstIndex <= first.length || secondIndex < second.length) {
if (first[firstIndex] < second[secondIndex]) {
result[resultIndex] = first[firstIndex];
firstIndex++;
} else {
result[resultIndex] = second[secondIndex];
secondIndex++;
}
//如果第一个数组先结束,则把第二个数组剩余元素直接放到结果中
if (firstIndex > first.length) {
addArr02(result, result.length + 1, second, secondIndex);
return result;
}
//如果第二个数组先结束,则把第一个数组剩余元素直接放到结果中
if (secondIndex > second.length) {
addArr02(result, first.length + 1, first, firstIndex);
return result;
}
resultIndex++;
}
return result;
}
public static int[] connectArr02(int FirstArr[], int SecondArr[]) {
int[] ResultArr = new int[FirstArr.length + SecondArr.length];
System.arraycopy(FirstArr, 0, ResultArr, 0, FirstArr.length);
System.arraycopy(SecondArr, 0, ResultArr, FirstArr.length, SecondArr.length);
return ResultArr;
}
public static int[] addArr02(int ResultArr[], int RArrIndex, int AddArr[], int AArrIndex) {
while (AArrIndex <= AddArr.length - 1) {
ResultArr[RArrIndex] = AddArr[AArrIndex];
AArrIndex++;
RArrIndex++;
}
return ResultArr;
}