排序算法,JAVA的。帮忙调下吧。

来源:百度知道 编辑:UC知道 时间:2024/05/30 20:22:03
//归并排序
public class px_10 {
public static void main(String args[]) {
int array[]={2,99,87,31,45,6,5,43,15,33,32,54,21,71,0,50,1,10};
Msort sort10=new Msort();
sort10.Mersort(array,0,array.length-1);
for(int k=0;k<array.length;k++)
System.out.print(" "+array[k]);
}//main
}//class

class Msort {

static void Mersort(int []array,int l,int r) {
int temp[]=new int[18];
int mid=(l+r)/2;

if(l<r) {
Mersort(array,l,mid);
Mersort(array,mid+1,r);
Merge(array,temp,l,r);
}//if

}//Mersort

static void Merge(int array[],int []temp,int l,int r) {
int i,j,mid=(l+r)/2,k=-1;
while(l<r) {
for(i=l,j=mid+1;i<=mid&&j<=r; ) {
if(array[i]<=array[j])
temp[++k]=array[j++];
else temp[++k]=array[j++];
}//for
if(i==mid) {
while(

你的那个程序自增运算前后不一致,temp[++k]=array[j++];temp[++k]=array[++i];漏掉了某些数。还有主while循环很不必要,导致k一直增加,而ij没变化。我从新实现了算法,用netbeans 6.7调试过的。你把两者对比看下。
class Msort {
static int[] temp=new int[18];
static void Mersort(int []array,int l,int r) {

int mid=(l+r)/2;

if(l<r) {
Mersort(array,l,mid);
Mersort(array,mid+1,r);
Merge(array,l,r);
}

}//Mersort

static void Merge(int array[],int l,int r) {
int i,j,mid=(l+r)/2,k=l;
if(l<r) {

for(i=l,j=mid+1;i<=mid&&j<=r; ) {
if(array[i]<=array[j])
temp[k++]=array[i++];
else temp[k++]=array[j++];
}//for

while(j<=r)
temp[k++]=array[j++];

while(i<=mid)
temp[k++]=array[i++];

f