# Thread: InsertionSort My SourceCode - wrong results

1. Member
Join Date
Nov 2008
Posts
1
Rep Power
0

## 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

Java 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];

• To begin with, line 33 won't let it compile:

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

Java 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:
Java Code:
`z = a[i-1];   // exchange them`
be like this:
Java Code:
`a[i-1] = z;   // exchange them`
Luck,
CJSL

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•