简体   繁体   中英

sorting an array and counting its elements

I tried to sort an array accending and count the array elements please help me find whats missing, have debugged many times. here is my code and the output i got. Thanks

package habeeb;

import java.util.*;

public class Habeeb {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int[] num = new int[30];
        int i, count=0;

        System.out.println("Enter the integers between 1 and 100" );

        for( i=0; i<num.length; i++){
            num[i]= input.nextInt();
            if(num[i]==0)
                break;
            count++;
        }

calling the function here

        Sorting(num, i, count);
    }

    public static void Sorting(int[] sort, int a, int con){
        if (a<0) return;
 /*am sorting the array here*/
        Arrays.sort(sort); 
        int j, count=0;

        for(j=0; j<con; j++){
            if(sort[a]==sort[j])
                count++;
        }

        System.out.println(sort[a]+" occurs "+count+" times"); 
        Sorting(sort, a-1, con);
    }
}

Here is the output:

run:
Enter the integers between 1 and 100
2
5
4
8
1
6
0
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times
0 occurs 6 times

Your problem is that the array is of size 30 and when you sort it you have all the values you did not assign to equal to 0 and thus they go in the front of the sorted array. Later on out of the first 6 numbers all are 0 so the output you have is correct.

To aviod the problem you face I suggest you use ArrayList instead of simple array so that you can add elements dynamically to it.

You are doing a bit more work than is necessary. I would solve this like so:

Map<Integer, Integer> countMap = new HashMap<Integer,Integer>();  


for( i=0; i<num.length; i++){
    int current = input.nextInt();  
    if(countMap.get(current) != null)  
    {  
        int incrementMe = countMap.get(current);  
        countMap.put(current,++incrementMe);  
    }  
     else  
     {  
         countMap.put(input.nextInt(),1);  
     }  
}

Try this

The counting method

public int count(int[] values, int value)
{
    int count = 0;
    for (int current : values)
    {
        if (current == value)
            count++;
    }
    return count;
}

Then use

int[] sorted = Arrays.sort(num);
for (int value : sorted)
{
    System.out.println("" + value + " occurs " + count(sorted, value) + " times");
}

This works for sure.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM