数据结构--归并排序

来源:互联网 发布:手机淘宝模板怎么设置 编辑:程序博客网 时间:2024/06/07 12:32
归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。我们首先来看看如何将两个有序的数组拼接到另外一个数组里且保持有序;

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  




0 0
原创粉丝点击