数据结构--归并排序
来源:互联网 发布:手机淘宝模板怎么设置 编辑:程序博客网 时间:2024/06/07 12:32
public static void main(String[] args){
guibing g = new guibing();
int a[]={1,4,3,7,2,6,4};
int b[]={2,4,5,6,8,8,9,10};
int c[] = new int[a.length+b.length];
System.out.println("a数组元素为:");
g.print(a);
System.out.println("b数组元素为:");
g.print(b);
System.out.println("c数组元素为:");
g.print(c);
g.Connect(a, b, c);
System.out.println("连接以后的数组元素为:");
g.print(c);
}
public void Connect(int a[],int b[],int c[]){
int afirst=0;
int bfirst=0;
int cfirst=0;
while(afirst<a.length&&bfirst<b.length)
{
if (a[afirst]<=b[bfirst]) {
c[cfirst++]=a[afirst];
afirst++;
}else{
c[cfirst++]=b[bfirst];
bfirst++;
}
}
while (afirst<a.length) {
c[cfirst]=a[afirst++];
}
if (bfirst<b.length) {
c[cfirst]=b[bfirst++];
}
}
public void print(int a[]){
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println(" ");
}
运行结果:
a数组元素为:
1 2 4 5 6
b数组元素为:
2 4 5 6 8 10 12
c数组元素为:
0 0 0 0 0 0 0 0 0 0 0 0
连接以后的数组元素为:
1 2 2 4 4 5 5 6 6 8 10 12
*********************************************************下面进入归并排序的环节:
//归并连接部分
public void connect1(int a[],int low,int mid,int high){
int c1=low;
int c2 = mid+1;
int b[]=new int[a.length-1];
b=a.clone();
while(c1<=mid&&c2<=high){
if (b[c1]<=b[c2]) {
a[low++]=b[c1++];
}else{
a[low++]=b[c2++];
}
}
while (c1<=mid) {
a[low++]=b[c1++];
}
while (c2<=high) {
a[low++]=b[c2++];
}
}
//归并递归部分,不断分割
public void merge(int a[],int low,int high){
if (low<high)
{
int mid = (high+low)/2;
merge(a, low, mid);
merge(a, mid+1, high);
connect1(a, low, mid, high);
}
}
//用于输入待排序的数组
public int[] inputArray(){
int b[] = null;
Scanner in=new Scanner(System.in);
int n,i;
System.out.print("请输入数组a[]的元素个数:");
try{
n=in.nextInt();
int[] a=new int[n];
for(i=0;i<n;i++){
System.out.print("请输入数组a["+i+"]:");
a[i]=in.nextInt();
}
b=a.clone();
in.close();
System.out.println("输入的数组为:");
for(i=0;i<n;i++)
System.out.print(a[i]+" ");
System.out.println(" ");
}
catch(Exception e){
e.printStackTrace();
}
return b;
}
请输入数组a[]的元素个数:8
请输入数组a[0]:2
请输入数组a[1]:1
请输入数组a[2]:5
请输入数组a[3]:3
请输入数组a[4]:6
请输入数组a[5]:7
请输入数组a[6]:2
请输入数组a[7]:0
输入的数组为:
2 1 5 3 6 7 2 0
a数组元素为:
2 1 5 3 6 7 2 0
归并排序以后的元素:
0 1 2 2 3 5 6 7
- 数据结构--归并排序
- 数据结构 排序 归并排序
- 【数据结构】:排序--归并排序
- 数据结构排序--归并排序
- 数据结构之归并排序
- 数据结构--归并排序
- 【数据结构】归并排序
- 数据结构 - 归并排序
- C++数据结构--归并排序
- 数据结构-归并排序
- 数据结构归并排序实现
- 数据结构之归并排序
- 数据结构之归并排序
- 数据结构(8) 归并排序
- [数据结构] 归并排序算法
- 【数据结构】-归并排序,基数排序
- 数据结构--向量--归并排序
- 数据结构 — 归并排序
- Hi
- RRC概述
- JAVA IO-----字节流与字符流
- 字典树模板
- Java基础知识-正则表达式
- 数据结构--归并排序
- 数据结构--栈的顺序存储
- 数据结构--链表的操作(顺序结构)
- 数据结构---链表操作(线性结构)
- 各种排序的总结
- java开发-abstract类、final类
- Java 开发---DOS 下运行java程序
- 【GDOI2016】中学生数学题 题解
- Java开发--static,final,transient