How can I fix an error in the insertion sort while loop in a Java program?

  • Comp Sci
  • Thread starter apiwowar
  • Start date
  • Tags
    Java Sort
Among other things, it will let you execute the program one statement at a time, inspecting variables as you go.In summary, the conversation is about fixing a program that was given to the speaker. They have found an error in the insertion sort part but are having trouble getting the while loop to run. They are limited in making fundamental changes to the program and are seeking advice or pointers to help them fix the error. They also discuss the use of a debugger to aid in debugging.
  • #1
apiwowar
96
0
So i haven't done java in about two years, its been a while since I've seen arrays. THe assignment is to fix a program that was given to me. I found one error but in the insertion sort part i can't get it to run the while loop. I can't make any fundamental changes to the program, basically i just have to fix the error in the while loop to get it running.

any pointers or advice would be appreciated, just need a kick in the right direction.

below is the program



import java.io.*; // for BufferedReader
import java.util.*; // for StringTokenizer

public class Prog1Original { // A simple program with no classes

public static void main(String[] args) throws IOException {

int number[] = new int[100];
int ct, num, size, i, j, insel;
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in) );

System.out.print("Input integers: ");
size = 0; // The smallest index of an array is always 0
String inputLine = stdin.readLine(); // All input must be on a single line
StringTokenizer input = new StringTokenizer(inputLine);
while (input.hasMoreTokens()) { // extract the integers from the input line

num = Integer.parseInt(input.nextToken());
number[size] = num;
size = size + 1;
}
System.out.println();
System.out.print("The original numbers: ");
for (ct = 0; ct < size; ct++) {
System.out.print(number[ct]);
System.out.print(" ");
}
System.out.println();

// "Insertion Sort" the numbers
for (i = 1; i < size; i++) { // Starting with the second array element
insel = number;
j = i;
while ( (number[j] > insel) && (j >= 0) ) { // shift larger elements right
number[j + 1] = number[j];
j = j - 1;
}
number[j] = insel; // insert the number to its proper place
}
System.out.print("The sorted numbers: "); // Output the sorted array
for (ct = 0; ct < size; ct ++) {
System.out.print(number[ct]);
System.out.print(" ");
}
System.out.println();
}
}
 
Physics news on Phys.org
  • #2
I added (code) and (/code) tags (but in square brackets) to preserve your original formatting.
apiwowar said:
So i haven't done java in about two years, its been a while since I've seen arrays. THe assignment is to fix a program that was given to me. I found one error but in the insertion sort part i can't get it to run the while loop. I can't make any fundamental changes to the program, basically i just have to fix the error in the while loop to get it running.

any pointers or advice would be appreciated, just need a kick in the right direction.

below is the program


Code:
import java.io.*;    // for BufferedReader
import java.util.*;  // for StringTokenizer

public class Prog1Original { // A simple program with no classes

   public static void main(String[] args) throws IOException {

      int number[] = new int[100];
      int ct, num, size, i, j, insel;
      BufferedReader stdin = new BufferedReader(
         new InputStreamReader(System.in) );

      System.out.print("Input integers: ");
      size = 0;  // The smallest index of an array is always 0
      String inputLine = stdin.readLine();    // All input must be on a single line
      StringTokenizer input = new StringTokenizer(inputLine);
      while (input.hasMoreTokens()) {  // extract the integers from the input line
         
         num = Integer.parseInt(input.nextToken());
         number[size] = num;
         size = size + 1;
      }
      System.out.println();
      System.out.print("The original numbers: ");
      for (ct = 0; ct < size; ct++) {
         System.out.print(number[ct]);
         System.out.print("  ");
      }
      System.out.println();

       // "Insertion Sort" the numbers
      for (i = 1; i < size; i++) { // Starting with the second array element
         insel = number[i];
         j = i;
         while ( (number[j] > insel) && (j >= 0) ) { // shift larger elements right
            number[j + 1] = number[j];
            j = j - 1;
         }
         number[j] = insel;  // insert the number to its proper place
      }
      System.out.print("The sorted numbers: ");  // Output the sorted array
      for (ct = 0; ct < size; ct ++) {
         System.out.print(number[ct]);
         System.out.print("  ");
      }
   System.out.println();
   }
}

Can you give more details about what you mean that you can't get it to run the while loop. If a while loop isn't executing, it's because the test condition at the top of the loop is false. That means that number[j] <= insel or j < 0, or both.
 
  • #3
i put in System.out.print(" " + j); into the while loop to see if it would print out anything while doing the loop. my thinking was that if it did then the program goes through the loop but it didnt print that out which leads me to think that it doesn't go through the loop.
 
  • #4
Right. If you don't have a debugger to work with, or do have one but don't know how to use it, put a print statement just before the start of the loop to display the values of j and number[j].

If you have a debugger available, it would be a very good idea to learn how to use it.
 
  • #5


As a scientist, my advice would be to first understand the purpose and logic behind the insertion sort algorithm. This will help you identify any potential errors in the code and make the necessary changes. Additionally, it might be helpful to review the basics of arrays in Java to refresh your memory. You can also try debugging the code by printing out the values of the variables at each step to see where the error is occurring. Finally, don't be afraid to ask for assistance from your colleagues or online resources. With some persistence and effort, you should be able to fix the error and get the program running smoothly.
 

FAQ: How can I fix an error in the insertion sort while loop in a Java program?

What is insertion sort in Java?

Insertion sort is a sorting algorithm in Java that takes an unsorted array and sorts it in ascending order by inserting each element into its proper position in the sorted subarray. It is an efficient and simple sorting algorithm that works well for small or partially sorted arrays.

How does insertion sort work in Java?

Insertion sort works by iterating through the unsorted array and "inserting" each element into its proper position in the sorted subarray. This is done by comparing each element with the elements in the sorted subarray and moving them to the right if they are greater than the current element being inserted.

What is the time complexity of insertion sort in Java?

The time complexity of insertion sort in Java is O(n^2), where n is the number of elements in the array. This means that as the size of the array increases, the time taken to sort it also increases exponentially.

How can insertion sort be implemented in Java?

Insertion sort can be implemented in Java using a simple for loop to iterate through the unsorted array, and another for loop to compare the current element being inserted with the elements in the sorted subarray. The elements are then shifted to the right until the correct position is found, and the current element is inserted in that position.

When is insertion sort a good choice in Java?

Insertion sort is a good choice in Java when the input array is small or partially sorted. It is also a good choice when the array is almost sorted, as it has a best-case time complexity of O(n), making it more efficient than other sorting algorithms. However, it is not a good choice for large or unsorted arrays, as it has a high time complexity compared to other sorting algorithms such as merge sort or quick sort.

Similar threads

Replies
7
Views
2K
Replies
12
Views
2K
Replies
5
Views
2K
Replies
1
Views
2K
Replies
2
Views
1K
Replies
2
Views
18K
Replies
6
Views
3K
Replies
6
Views
1K
Replies
7
Views
2K
Back
Top