I need to generate 500 random numbers from 200 to 1200 and use insertion to sort them. This is probaly simple for you guys but im confused. My problem is when i run the program all I get is 500 0's. Anyone help me out?

public class insertion{
public static void main(String arg[]){
	int n = 500;
	int[] a = new int[n];
	System.out.println("\n\nInput values:");
	for(int i=0;i<n;i++){
		System.out.print(" "+a[i]);
		}
	for (int i = 1; i < a.length; i++) {
	    int j = i;
	    int B = 200 + (int)(Math.random() * ((1200 - 200) + 1));
	    B = a[i];
	    while ((j > 0) && (a[j-1] > B)) {
               
	        a[j] = a[j-1];
	        j--;
	     }
	    a[j] = B;           
        }
	System.out.println("\n\n\nSorted values:");
	for(int i=0;i<a.length;i++)
		{
	System.out.print(" "+a[i]);
	    }
}
}

Line 11, using Math.random() is dangerous because of the type casting. Use nextInt() of Random class instead.

Random r = new Random();
int B = 200+r.nextInt(1000);  // between 200~1200

You forget to give a random value to your a[0] before you go inside the loop. Also, your line 12, should it be that way? The reason is that your line 12 will always assign '0' to B and overwrite whatever B value you computed...

If you track your loop, you would see why it results that way... Write the value down for each a[j] and a[j-1] while you are going through each j.

commented: helped me +0

your Line 7 has a problem
you have created an array which is a[500];
in which there is no VALUE
and you are printing that instead of taking values
so check that

Hi javaflasher.
No disrespect, but have you checked a calendar recently? That problem was posted March 3rd. The OP will have either solved it or given up many months ago.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.