# Sort Problem

Printable View

• 03-11-2012, 06:40 PM
JeremyLin
Sort Problem
Hey guys,
I'm trying to solve a problem in which the user keeps inserting numbers and everytime the user inserts a number the problem should sort the array.

This is the code I've done :
Code:

```public class ex5 {     public static void main(String Args[]){         Scanner input = new Scanner(System.in);         System.out.println("Quantos inteiros quer ler?");         int n_inteiros = input.nextInt();         int[] a = new int[n_inteiros];         for(int i=0;i<n_inteiros;i++){         a[i]=0;         }         int i=0;         while(i<n_inteiros){             int novo= input.nextInt();             a[i]=novo;             Arrays.sort(a);             i++;         }         System.out.println("Estado final do array:");         for(int j=0;j<n_inteiros;j++){             System.out.println(a[j]);         }     } }```
Now the output :
Code:

```Quantos inteiros quer ler? 3 1 2 3 Estado final do array: 0 1 3```
Any help please ?
Thanks.
• 03-11-2012, 08:03 PM
Norm
Re: Sort Problem
Try adding a print out of the array after every sort to see what is in it. Use the Arrays toString() method to format the array:
S.o.println(Arrays.toString(a));

This will help you understand what the code is doing.
• 03-11-2012, 08:20 PM
JeremyLin
Re: Sort Problem
Thanks Norm.
What's the S.o. for ?
I'm still a beginner :/
• 03-11-2012, 08:24 PM
Norm
Re: Sort Problem
Sorry. S.o. should be System.out.
• 03-11-2012, 08:32 PM
JeremyLin
Re: Sort Problem
Wow, that's amazing.
Thanks a lot Norm.

Code:

```1 [0, 0, 1] 2 [0, 1, 2] 3 [0, 1, 3]```
That's what it does.
Basically it works until the 3, when we hit the three it replaces the last int for the 3 :o
I have no idea why though :/
• 03-11-2012, 08:49 PM
Norm
Re: Sort Problem
Take a piece of paper and draw the array and set the value of i. change the array's contents at i and sort the array and increment i.
Do it again. Do you ever put an item into the array where there is currently another number? If so you replace that number.

Work through your code playing comuter with paper and pencil and you will see what it is doing.

Quote:

when we hit the three it replaces the last int for the 3
What is the value of i?
• 03-12-2012, 07:23 AM
waiheng1986
Re: Sort Problem
I think you should sort the integer array after the integer from user is been inserted into the integer array.
This should be sort correctly everytime you print it at the end.

Hope this can help you.