I just want to sort the array of numbers by the sort method. But unfortunately it throws an error:
java.lang.ArrayIndexOutOfBoundsException:10 at Search.sort(Search.java:30) at Search.main(Search.java:67)
Here is my code:
import java.util.Scanner;
public class Search {
public Search() {
System.out.println("inside a constructer");
}
public int[] sort(int x[]) {
for (int i = 0; i < x.length - 1; i++)
for (int j = 1; j < x.length; j++) {
int temp;
if (x[i] > x[j]) {
temp = x[i];
x[i] = x[j];
x[j] = x[i];
}
}
return x;
}
public static void main(String[] args) {
// System.out.println("fgdg"+num);
int num[] = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("Eneter the 10 integers:");
for (int i = 0; i < 10; i++) {
System.out.println("Enter the " + (i + 1) + " number:");
num[i] = sc.nextInt();
}
System.out.println("before sorting:");
for (int m = 0; m <= num.length; m++)
System.out.println(num[m]);
Search obj = new Search();
int x1[] = obj.sort(num);
System.out.println("sorted:");
for (int k = 0; k <= x1.length; k++)
System.out.println(x1[k]);
}
}