0

enter image description hereThe following is code for the merge sort. I am getting an error on the last line. I have also added a comment. I am unable to retrieve the array returned by the method merge_function(int[] a, int[] b). The error says " non-static method merge_sort(int[],int,int) cannot be referenced from a static context at demo1.Merge.main". Please help..!

public class Merge {
    int[] merge_sort(int[] arr, int s, int e){
        if(arr.length==1)
            return arr;
        int m=(s+e)/2;
        int []a= merge_sort(arr,s,m);
        int []b= merge_sort(arr,m+1,e);
        int []c= merge(a,b);
        print(arr);
        return c;

    }
    public void print(int[] arr)
    {
        System.out.println("Elements after sorting:");
        for(int i=0;i<arr.length;i++)
        {
            System.out.print(arr[i]+" ");
        }
    }
    int[] merge(int[] a, int[] b)
    {
        int i=0,j=0,k=0;
        int []r=new int[a.length+b.length];
        while(i!=a.length && j!=b.length)
        {
            if(a[i]<b[j])
            {
                r[k]=a[i];
                i++; j++; k++;
            }
            else if(a[i]==b[j])
            {
                r[k]=a[i];
                i++; j++; k++;
            }
            else if(a[i]>b[j])
            {
                r[k]=b[j];
                j++; k++;
            }
        }
        return r;
    }
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the length of an array.");
        int n=in.nextInt();
        System.out.println("Enter the numbers.");
        int arr[]=new int[n];
        for(int i=0;i<n;i++)
        {
            arr[i]=in.nextInt();
        }

        //error is here
        int []r = merge_sort(arr,0,arr.length-1);
    }
}
  • @jsheeran the error says "Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - non-static method merge_sort(int[],int,int) cannot be referenced from a static at demo1.Merge.main(Merge.java:72)" – Tenzin Tridhe Mar 08 '18 at 14:43
  • 1
    You either need to rewrite your `main()` method to create an instance of your class and then handle the logic from that instance, or declare all the relevant methods as `static`. – jsheeran Mar 08 '18 at 14:44
  • 3
    Possible duplicate of [Non-static variable cannot be referenced from a static context](https://stackoverflow.com/questions/2559527/non-static-variable-cannot-be-referenced-from-a-static-context) – jsheeran Mar 08 '18 at 14:45

1 Answers1

0

you cannot call non-static methods from a static context without using an instance of the class containing those methods.

sharon182
  • 533
  • 1
  • 4
  • 19