MergeSort-我在java中的第一个DS算法

时间:2015-10-03 17:22:51

标签: java algorithm sorting mergesort

package allSortings;
import java.util.Scanner;
public class MergeSort {
public static int A[],B[];
void mergeArray(int A[],int first,int mid,int last){
    int i=first,j;
    j=mid;
    while(i<=mid && j<=last)
    {
        if(A[i]<A[j])
            B[first++]=A[i++];
        else B[first++]=A[j++];
    }

    while(i<=mid)
        B[first++]=A[i++];
    while(j<=last)
        B[first++]=A[j++];
}
void copyArray(int A[],int last,int B[])
{
    int i=0;
    while(i<last)
    {
        A[i]=B[i];i++;
    }
}
void splitArray(int A[],int first,int last)
{
    if(first<last)
    {
        int mid=first+last/2;
        System.out.println("first:"+first);
        splitArray(A,first,mid);
        splitArray(A,mid+1,last);
        //mergeArray(A,first,mid,last);
        //copyArray(A,last,B);
    }
}

public static void main(String args[])
{

    int n;
    A=new int[100];
    B=new int[100];
    System.out.println("Enter the no. of elements in the Array:"+"\n");
    Scanner input;
    input=new Scanner(System.in);
    n=input.nextInt();
    MergeSort m1=new MergeSort();
    for(int i=0;i<n;i++)
        A[i]=input.nextInt();
        System.out.println("\nThe Original array is:");
        for(int i=0;i<n;i++)
            System.out.format("%d"+" ",A[i]);
        m1.splitArray(A,0,n-1);
        System.out.println("\nThe Sorted array is:");
        for(int i=0;i<n;i++)
            System.out.format("%d"+" ",A[i]);
}

}

我一直在allSortings.MergeSort.splitArray(MergeSort.java:34)。任何线索(我是Java新手,所以我不知道使用调试器)? “first”变量的值总是为2,然后不会改变。

1 个答案:

答案 0 :(得分:0)

您只需将一个加数除以2,但您应该将总和除以2。取代

int mid=first+last/2;

int mid=(first+last)/2;