任意两整数数组排序

xuancao 2004-02-23 09:45:26
/*
*@description : 实现任意两整数数组的按从小到大重组
* 先排序,再重组
*@Author : dalily
*@Date : 2004-2-22
*/
public class ArraySortClass{

//测试方法,先排序后重组
public static void main(String args[]){
int[] A ={12,8,6,15,10,17};
int[] B ={7,11,13,2,9,3};

//对数组排序
int[] A1 = bubbleSort(A);
int[] B1 = bubbleSort(B);

//对数组重组
int[] C = assembleArray(A,B);
//输出数组
for (int m=0;m<12;m++){
System.out.println("the C is :" + C[m]);
}
}

/*
* 实现两个有序整数数组按从小到大的顺序重组
* 三个过程:1.按顺序比较两个数组中数据,只到其中一个已经没有剩余数据
* 2.如果比较后的A数组还有剩余,则把A数组的其余数据补充到C数组
* 3.如果比较后的A数组还有剩余,则把A数组的其余数据补充到C数组
* @param A : the first Array
* @param B : the second Array
* @result : the assembled Array
*/
public static int[] assembleArray(int[] A, int[] B){
int iALength = A.length;
int iBLength = B.length;
int[] C = new int[iALength + iBLength];
int i=0;
int j=0;
int k=0;

//按顺序比较两个数组中数据,只到其中一个已经没有剩余数据
while (i<iALength && j <iBLength){
if (A[i] <=B[j]){
C[k] = A[i];
i++;
} else{
C[k] = B[j];
j++;
}
k++;
}

//如果比较后的A数组还有剩余,则把A数组的其余数据补充到C数组
if (i<iALength){
for (int m=i;m<iALength;m++){
C[k] = A[m];
k++;
}
}

//如果比较后的B数组还有剩余,则把B数组的其余数据补充到C数组
if (j<iBLength){
for (int n=j;n<iBLength;n++ ) {
C[k] = B[n];
k++;
}
}
return C;
}

/*
* 采用冒泡排序实现整数数组排序
* @param A : the before Array
* @param B : the sorted Array
*/
public static int[] bubbleSort(int A[]){
int iAlength = A.length;
int i = 0;
int k = 0 ;
int temp = 0;
while (i < iAlength){
for (k=i+1;k<iAlength;k++){
if (A[k]<A[i]){
temp = A[i];
A[i] = A[k];
A[k] = temp;
}
}
i++;
}
return A;
}
}
...全文
25 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧