364,083 Members | 5932 Browsing Online
Community for Developers & IT Professionals
Bytes IT Community

Java Error ArrayIndexOutOfBoundsException

Rohit Rane
P: 5
Expand|Select|Wrap|Line Numbers
  1. class selection
  2. {
  3.     public static void sort(int arr[])
  4.     {
  5.         for(int i= arr.length;i>0;i++)
  6.         {
  7.             int m=0;
  8.             for(int j=1;j<=i;j++)
  9.             {
  10.                 if(arr[j]>arr[m])
  11.                 {
  12.                     m=j;
  13.                 }
  14.             }
  15.             int temp= arr[i];
  16.             arr[i]= arr[m];
  17.             arr[m]= temp;
  18.         }
  19.         System.out.println("Array After Sort : ");
  20.         System.out.print("{");
  21.         for(int i=0;i<arr.length;i++)
  22.             System.out.println(arr[i]+",");
  23.         System.out.print("}");
  24.     }
  25.     public static void main(String args[])
  26.     {
  27.         int arr[] = {11,55,13,5,3};
  28.         System.out.print("Array before sort : ");
  29.         System.out.print("{");
  30.         for(int i=0;i<arr.length;i++)
  31.             System.out.print(arr[i]+",");
  32.         System.out.println("}");
  33.         sort(arr);
  34.     }
  35. }
Output :
Array before sort : {11,55,13,5,3,}
Excepion in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at selection.sort(selection.java:10)
at selection.main(selection.java:33)
Jan 29 '12 #1
Share this Question
Share on Google+
6 Replies


Rabbit
Expert Mod 5K+
P: 6,662
You're going out of bounds in the first for loop in the sort function.
Jan 29 '12 #2

Rohit Rane
P: 5
so what changes in code should i do
Jan 30 '12 #3

Rabbit
Expert Mod 5K+
P: 6,662
Well you should probably initialize i to 0 and the continue condition should be i < arr.length. But what you actually want to put in there is dependent on your business logic. You haven't explained what that is so I can't say what is correct. With the information you've given me, I can only tell you where it's wrong, not how to fix it.
Jan 30 '12 #4

Rohit Rane
P: 5
well this is part of data structure in java
topic named is Selection sorting
n tnx for replying u r answer will be well appretiated
Jan 30 '12 #5

Rabbit
Expert Mod 5K+
P: 6,662
It sounds like you're just doing a bubble sort. In which case you should change those values to the ones I listed in the fourth post.
Jan 30 '12 #6

neeraj0708
P: 20
hi,

As array are "0 based index" and you are running the loop more than its length in first for loop. and incrementing the value of i.

try this

for(int i= arr.length-1;i>0;i--)

Hope it will work fine.
Feb 9 '12 #7

Post your reply

Help answer this question



Didn't find the answer to your Java question?

You can also browse similar questions: Java