Richa Srivastava
Richa Srivastava

Reputation: 3

Array elements become 0 after applying Array.sort() function

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?

Upvotes: 0

Views: 1415

Answers (2)

Shweta Singh
Shweta Singh

Reputation: 31

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.

Upvotes: 1

ROMANIA_engineer
ROMANIA_engineer

Reputation: 56636

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.

Upvotes: 2

Related Questions