PROBLEM STATEMENT : Consider an array of numeric strings, , where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing (i.e., ascending) order of their real-world integer values and print each element of the sorted array on a new line.
"As input array consist strings of integers, to sort it in ascending order we need to compare evry element present in it but as integers are in the form of strings it need to be converted into Int data type.
if someone could suggest me where i am going wrong in my code. i would be exteremly grateful!
I am not sure whether there is some logical error in my code or not but but a runtime error " array IndexOutOfBounds" occures during execution of code.
PS:I have tried my level best and still can't able to figure out my Mistake. so plz do not downvote its a request.
public static void main(String[] args)
{
int temp=0;;
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[]arr = new String[n];//array of numeric string
int[]array = new int[n];
for(int unsorted_i=0; unsorted_i < n; unsorted_i++){
arr[unsorted_i] = in.next();
}
for(int i=0;i<n-1;i++)//logic for sorting arrays
{
for(int j=0;j<n;j++)
{
array[i] =Integer.parseInt(arr[i]);//arr is array of string datatype
array[j] =Integer.parseInt(arr[j]);
if(array[i]>array[j])
{
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
for(int i=0;i<n;i++)
System.out.println(array[i]);
}
}
Error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Solution.main(Solution.java:23)