# InsertionSort My SourceCode - wrong results

• 11-27-2008, 12:57 AM
JohnF8FJohn
InsertionSort My SourceCode - wrong results
I've writte an InsertionSort
It runs so far, but it delivers the wrong results so the code for the sorting must have a mistake. code lines 22-33 must not be working accordingly, but i dont see whats wrong

Code:

``` import java.util.Scanner; public class sort4 {   public static void main(String args[]) {       Scanner nutzerEingabe = new Scanner(System.in);       System.out.print("InsertionSort: Enter a number ");       int zahl = nutzerEingabe.nextInt();              String x = ""+zahl; //String for length         int len = x.length();//of the number         int [] a = new int[len];// Create array with that length                 // Get number into array         for(int k=1;k<len;k++){             int ziffer =zahl%10;             zahl = zahl/10;             a[k]=ziffer;         }         // Insertion Sort starts         int z,y,compareX=0;       for (int i=1; i<len; i++) {         compareX++;    // counts comparisons         z = a[i];      //Int-value at position i         y = a[i-1];      //Int-value left of it         while (y>=0 && y > z){// if left side is bigger than z             z = a[i-1];  // exchange them                         y--;         }y = a[i];       }/[b]       for (int l=0;l<len;l++){// output       System.out.print(""+a[l]);       }       System.out.println("\tresult after "+compareX+" comparisons");   } }```
// Insertion Sort starts
int z,y,compareX=0;
for (int i=1; i<len; i++) {
compareX++; // counts comparisons
z = a[i]; //Int-value at position i
y = a[i-1]; //Int-value left of it
while (y>=0 && y > z){// if left side is bigger than z
z = a[i-1]; // exchange them

y--;
}y = a[i];
• 11-27-2008, 02:11 AM
CJSLMAN
• To begin with, line 33 won't let it compile:

Code:

`}/[b] <-makes compiler upchuck`
• Another observation would be the following piece of code:

Code:

```for(int k=1;k<len;k++){             int ziffer =zahl%10;             zahl = zahl/10;             a[k]=ziffer;```
Not sure what you're trying to do here, but is zahl in the right position?... Should the zahl assignment before the ziffer assignment?
• Line 27: If you are going to swap the y-z values, shouldn't the following assigment:
Code:

`z = a[i-1];  // exchange them`
be like this:
Code:

`a[i-1] = z;  // exchange them`
Luck,
CJSL