0

This program is basic insertion sort. I am getting ArrayIndexOutOfBoundsException at line numbers 22 and 44. Help me in solving this issue.How to return sorted whole array from insertion method. return a[] is not working..............................................

package analysis;

import java.util.*;

class Sort
{
    int i,j,n,temp;
    int a[] = new int[n];

    int insertion(int a[],int n)
    {
        for (i=1;i<n;i++) {
            j=i-1;
            while (i>0 && a[j]>a[i]) {
                temp = a[j];
                a[j] = a[i];
                a[i] = temp;
                i--;
                j--;
            }
        }
        return a[n];
    }
}

class Recurse
{
    private static Scanner sc;

    public static void main(String[] args)
    {
        System.out.println("enter array size");
        int l,s;
        sc = new Scanner(System.in);
        s = sc.nextInt();
        int b[] = new int[s];
        int c[] = new int[s];
        for (l=0;l<s;l++) {
            b[l] = sc.nextInt();
        }
        Sort so = new Sort();
        c[s] = so.insertion(b,s);
        System.out.println("Sorted array is ");
        for (l=0;l<s;l++) {
            System.out.println(c[l]);
        }
    }
}
Yash
  • 1
  • 1

2 Answers2

1

Those two lines of your code causes the problem:

int a[] = new int[n];
return a[n];

Returning the element at n index is impossible because indexing include numbers from 0 to n-1.

Wojtek
  • 1,288
  • 11
  • 16
  • How to return the whole sorted array, from insertion method given above.Thanks in Advance :) – Yash Oct 02 '16 at 17:35
  • If you want to return the array in a function it should look like: int[] function() { int[] array = new int[10]; return array; } Please accept my answer as the correct one if it helps, cheers! – Wojtek Oct 03 '16 at 08:56
0

At line 44 you try to access c[l] from 0 to s but you only declared c[s]