#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    6
    Rep Power
    0

    Sorting Question


    I'm trying to write a program that generates 100 random number, prints them, then sorts them, then prints out the sorted list with ten numbers in each line. I cannot figure out what is wrong with my code. Anyone have any ideas? A detailed explanation would be awesome as I am new to this. This is what I have so far.

    Code:
    public class Main {
    
    	public static void main(String[]Args)
    	{
    		int [] b;
    		b = new int[100];
    		loadArray(b);
    		printArray(b);
    		Sort(b); 
    		printArray(b);
    	}
    
    	public static void loadArray(int[] b) {
    		for(int i = 0; i < b.length; i++){
    			b[i]= (int)((Math.random())*100)+1;{
    				
    			}
    		}
    		
    	}
    	
    	public static void printArray(int[] b){
    		System.out.println();
    		for(int i = 0; i < b.length; i++){
    			System.out.print(b[i]);
    			if((i + 1)%10 == 0)
    				System.out.println();
    		}
    	}
    	
    	public static void Sort(int [] b)
    	{
    		int Temp = 0;
    		for (int i = 0; i < b.length-1; i++)
    		{
    			for (int j = i + 1; j < b.length; j++)
    			{
    				if (b[i]> b[j])
    					{
    					Temp = b[i];
    					b[i] = b[j];
    					b[j] = Temp;
    					}
    			}
    			}
    			
    		}
    	
    
    }
    And here is an example of what it prints out right now.

    42629035334048469325
    21775561975248917456
    9340882010067304331
    5542393117952289996
    3775521286392295798
    83166760847191818556
    696337363376546310037
    99637451574393191
    54155896825250881413
    4479358294746523

    1244455688
    9111213141516202123
    23252829293031313333
    35363737373739394040
    42434546474848505252
    52525454545556565757
    58586061626363676769
    71747475767779818283
    84858688909191919393
    9393969696979899100100

    As you can see all of the lines have more than 10 numbers in them except for the first line of the sorted list, which is also the only line that is sorted. Any help would be appreciated, thanks.
  2. #2
  3. Java Junkie
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jan 2004
    Location
    Mobile, Alabama
    Posts
    4,020
    Rep Power
    1285
    The output you're seeing is because you didn't put spaces between the numbers.

IMN logo majestic logo threadwatch logo seochat tools logo