Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I really don\'t understand what the problem with my program is. I\'m trying to m

ID: 3597199 • Letter: I

Question

I really don't understand what the problem with my program is. I'm trying to make a gap sort and this is what I've got:

import java.util.Scanner;
public class GapSort{
public static void gapsort(Comparable[] arr){
  int index;
  int pos, i;
  Comparable temp;
  double sf=1.3;
  pos=arr.length-1;
  while(pos>1){
   pos=(int)(pos/sf);
   for(i=0;i<=arr.length-1-pos;i++){
    if(arr[i].compareTo(arr[i+pos])>0){
     temp=arr[i];
     arr[i]=arr[i+pos];
     arr[i+pos]=temp;
    }
   }
  }
}
public static void main(String[] args)
{
  Integer[]array={10,12,5,1039,53,94,201,195,1052};
  System.out.println("Unsorted:");
  System.out.println();
  for(int i=0;i<=array.length;i++){
   System.out.print(array[i]+ " ");
  }
  gapsort(array);
  for(int j=0;j<=array.length;j++){
   System.out.println(array[j]+ " ");
  }
}
}

But whenever I run the program, this is the display:

Unsorted:

10 12 5 1039 53 94 201 195 1052 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at GapSort.main(GapSort.java:26)

I don't understand what to do and I really need guidance on this.

Explanation / Answer

Lines in bold are modified.

There was very small fix : You are running for loop for n+1 times on array which is of length n. You put <= in   for(int j=0;j<=array.length;j++). It should be < only since the indices are in range from 0 to length-1.

Lines in bold are modified.

There was very small fix : You are running for loop for n+1 times on array which is of length n. You put <= in   for(int j=0;j<=array.length;j++). It should be < only since the indices are in range from 0 to length-1.

import java.util.Scanner;
public class GapSort{
public static void gapsort(Comparable[] arr){
int index;
int pos, i;
Comparable temp;
double sf=1.3;
pos=arr.length-1;
while(pos>1){
pos=(int)(pos/sf);
for(i=0;i<=arr.length-1-pos;i++){
if(arr[i].compareTo(arr[i+pos])>0){
temp=arr[i];
arr[i]=arr[i+pos];
arr[i+pos]=temp;
}
}
}
}
public static void main(String[] args)
{
Integer[]array={10,12,5,1039,53,94,201,195,1052};
System.out.println("Unsorted:");
System.out.println();
for(int i=0;i<array.length;i++){
System.out.print(array[i]+ " ");
}
gapsort(array);
System.out.println(" Items in sorted order are given below.");
for(int j=0;j<array.length;j++){
System.out.print(array[j]+ " ");
}
}
}
  Unsorted:  10 12 5 1039 53 94 201 195 1052     Items in sorted order are given below.  5 10 12 53 94 195 201 1039 1052