0

I am trying to sort an array of integers using Arrays.sort() method. After calling this method, the array elements are becoming 0.

Below is my code

import java.util.Arrays;
import java.util.Scanner;

public class WillMuggerWin {

  public static void main(String ar[]){
     int t,n=10,m=5,sum=0,flag=0;
     int notes[]=new int[20];

     Scanner s=new Scanner(System.in);
     t=s.nextInt();
     for(int i=0;i<t;i++){
         n=s.nextInt();
         m=s.nextInt();
         int temp=m;
        // System.out.println("m:"+m+"n:"+n);
         for(int j=0;j<n;j++){
             notes[j]=s.nextInt();

         }
         System.out.println("note:"+notes[0]+" "+notes[1]+" "+notes[2]);
         Arrays.sort(notes);
         System.out.println("note:"+notes[0]+" "+notes[1]+" "+notes[2]);
         //System.out.println("note1"+notes[0]);
         for(int k=n-1;k>=0;k--){
             //System.out.println("notes "+notes[k]);
             if(notes[k]<=temp){
                 sum=sum+notes[k];
                 System.out.println("sum: "+sum);
                 temp=temp-sum;
                 if(temp==0){
                     flag=1;
                     break;
                 }
             }
         }
         if(flag==1)
         System.out.println("Yes");
         else
             System.out.println("No");
         flag=0;
         sum=0;
     }
  }
}

Input:

5 3 3 1 1 1

Output:

note:1 1 1
note:0 0 0
sum: 0
sum: 0
sum: 0
No

What is wrong with my code?

2
  • 1
    What problem are you facing with this code? Commented Jan 14, 2017 at 17:38
  • 1
    After using Arrays.sort(notes) every element in the notes array is turning to zero. Commented Jan 14, 2017 at 17:42

2 Answers 2

2

Your array doesn't have only 3 elements, it's much longer because of this line:

int notes[] = new int[20];

If you want to see the cause of the problem, add the following line:

System.out.println(Arrays.toString(notes));

before your first:

System.out.println("note:"+notes[0]+" "+notes[1]+" "+notes[2]);

line and you will see the whole array:

[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

This is why you see 0s on the first 3 places after sorting, because that array also contains a lot of 0s after those 1s.

So, the sort method has the expected behavior.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh! great now I got it thanks for the help @RO_engineer
1

That is because one declares an array of larger length and insert values in array less than array's length.So in rest of the array 0 is stored.Hence when u sort and print, all the 0s come in the beginning.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.