This discussion is archived
13 Replies Latest reply: Apr 15, 2007 11:19 AM by 807599 RSS

Problem Sorting Partially Filled Arrays

807599 Newbie
Currently Being Moderated
I am having trouble sorting a partially filled array. What I want to have happen is have the user enter up to 50 numbers(int's only, 0's and negatives are allowed) and store the input in an array. Then sort the array, and display the sorted array from highest to lowest back to the user. The next step, which I haven't addressed yet is counting the number occurrences of each unique int and display that total to the user.

I have the array fill working correctly. Where I am having problems is when i try and sort the array of user entered values. Instead of only sorting the entered values, it add's "0's" to the array and sorts and displays them as well.

Here is what I want to have happen:

The user enters 1 2 3 4 3 2 1, the output should be 4 3 3 2 2 1 1. But what is actually being output is 4 3 3 2 2 1 1 0 0 0 0 0 0 etc.(until the array is full).

What am I doing wrong? If I display the contents of the array prior to sorting, it will only display the numbers entered, it does not add the extra 0's to fill the array. Any other suggestions on my code are welcome as well, always trying to get better at this, its tough teaching yourself form a book!

And I have left some of my tracer variables in there as well.
import java.util.Scanner;
import java.util.Arrays;

public class SortNumbers {
    //user can not enter more than 50 numbers to be sorted
    private static final int MAX_NUMBERS_ENTERED = 50;
    
    public static void main(String[] args) {
        // TODO code application logic here
        
        int[] sortThis = new int[MAX_NUMBERS_ENTERED];
        int numberUsed = 0;
        int count;
        System.out.println("Enter the numbers you would like to sort. Enter '1234' to stop. ");
        numberUsed = fillArray(sortThis);
        outputArray(sortThis, numberUsed);
        
    }
    
    //this receives numbers from the user
    public static int fillArray(int[] a){
        Scanner keyboard = new Scanner(System.in);
        
        int next;
        int index = 0;
        next = keyboard.nextInt();
        while ((next != 1234) && (index < a.length)){
            a[index] = next;
            index++;
            next = keyboard.nextInt();
        }    
        
        return index;
    }
    
    //this outputs the content of the array to the user
    public static void outputArray(int[] a, int numberUsed){
        //show the contents of the array
        System.out.println("The numbers you entered are: ");
        for (int i = 0; i < numberUsed; i++){
            System.out.print(a[i] + " ");
        }
        System.out.println();
        
        System.out.println("***********");
        System.out.println("array length: " + a.length + ", " + "what array length should be: " + numberUsed);
        System.out.println("***********");
        
        //sort the array and show the sorted output
        Arrays.sort(a);
        for (int i = (MAX_NUMBERS_ENTERED - 1); i >= 0; i--){
            System.out.print(a[i] + " ");
        }            
    }
}
  • 1. Re: Problem Sorting Partially Filled Arrays
    791266 Explorer
    Currently Being Moderated
    This line:
    for (int i = (MAX_NUMBERS_ENTERED - 1); i >= 0; i--)
    Makes you print the whole array, note that your other loop only prints as many as the user has entered.
  • 2. Re: Problem Sorting Partially Filled Arrays
    791266 Explorer
    Currently Being Moderated
    ... Do also note that you don't want to sort the whole array if the user only has entered a few values. You will get the wrong output if the user e.g enters 5,4,-1

    There is a sort method that takes indices:

    sort(int[] a, int fromIndex, int toIndex)

    Use that one instead.

    Kaj
  • 3. Re: Problem Sorting Partially Filled Arrays
    807599 Newbie
    Currently Being Moderated
    Hi,
            for (int i = (MAX_NUMBERS_ENTERED - 1); i >= MAX_NUMBERS_ENTERED - numberUsed; i--){
                System.out.print(a[i] + " ");
            }           
    Hope that help,
    Jack
  • 4. Re: Problem Sorting Partially Filled Arrays
    807599 Newbie
    Currently Being Moderated
    Hi,
            for (int i = (MAX_NUMBERS_ENTERED - 1);
    i >= MAX_NUMBERS_ENTERED - numberUsed; i--){
    System.out.print(a[i] + " ");
    hat help,
    Jack
    That does help, but doesn't work if the user enters a negative number. If the user enters: 1 2 3 4 -1, the output is: 4 3 2 1 0, instead of 4 3 2 1 -1.

    I appreciate the assistance!
  • 5. Re: Problem Sorting Partially Filled Arrays
    807599 Newbie
    Currently Being Moderated
    ... Do also note that you don't want to sort the
    whole array if the user only has entered a few
    values. You will get the wrong output if the user e.g
    enters 5,4,-1

    There is a sort method that takes indices:

    sort(int[] a, int fromIndex, int toIndex)

    Use that one instead.

    Kaj
    I have tried this as well in this format:
            //sort the array and show the sorted output
            Arrays.sort(a, 0, numberUsed);
            for (int i = (MAX_NUMBERS_ENTERED - 1); i >= 0; i--){
                System.out.print(a[i] + " ");
    The problem here is that when I print it out, it pads the beginning of the array with 0's, then places the numbers in the correct sorted format, from highest to lowest. It also correctly handles 0 and negative int inputs.

    If I use this and enter 1 2 3 0 -1, the output is 0 0 0 0 0 0 0 0 3 2 1 0 -1. How do I get rid of the preceding 0's?

    I feel that it has to have something to do with MAX_NUMBER_ENTERED, but if I put something else in place of it, I get only 0's as output.

    It's really stumping me!
  • 6. Re: Problem Sorting Partially Filled Arrays
    807599 Newbie
    Currently Being Moderated
    I actually just figured it out thanks to both of yours help!

    this is what I used to display the output correctly:
            //sort the array and show the sorted output
            Arrays.sort(a, 0, numberUsed);
            for (int i = (numberUsed - 1); i >= 0; i--){
                System.out.print(a[i] + " ");
            }
    Thanks to both of you for your help!

    Now I need to create a loop of some sort to count the number of times each unique number was entered by the user and output that to the screen. Would it be better to use a for loop to go through or a while loop?

    Anyways thanks to both of you for the help - now to dish out these Duke dollars...never done this before.
  • 7. Re: Problem Sorting Partially Filled Arrays
    791266 Explorer
    Currently Being Moderated
    Now I need to create a loop of some sort to count the
    number of times each unique number was entered by the
    user and output that to the screen. Would it be
    better to use a for loop to go through or a while
    loop?
    Doesn't matter if you create a for or while loop, but I think that most people would use a for loop since you know how many iterations you want to do.

    Kaj
  • 8. Re: Problem Sorting Partially Filled Arrays
    807599 Newbie
    Currently Being Moderated
    This is what I've gotten so far...
                   //sort the array and show the sorted output
            Arrays.sort(a, 0, numberUsed);
            int qty = 1;
            //show the headers of the columns
            System.out.println("Num" + "  " + "Qty");
            //go through the numbers and output them along with their qty
            for (int i = (numberUsed - 1); i >= 0; i--){      
                
                if (a[i] != a[i+1]) {
                    System.out.println(a[i] + "    " + qty);
                    qty = 1;                
                }
                else {
                    qty++;
                }
            }       
            System.out.println();
    However, it's not working. If I only enter 1 instance of each number it works fine. However, if i enter multiple instances of a number, it doesn't work how it should.

    Any suggestions? Should I replace the if statement with a for loop?

    In the same problem, I can't figure out how to only display the entered number once and the number of times that it has been displayed. I think my two problems go hand in hand, if I figure the first one out, the second one should be easy.
  • 9. Re: Problem Sorting Partially Filled Arrays
    807599 Newbie
    Currently Being Moderated
    Since you are iterating over the array backwards shouldn't you be comparing each number with the number before it not after it?
    if (a[i] != a[i - 1]) {
    Mind you this will generate an ArrayIndexOutOfBounds exception when you get to i = 0.
  • 10. Re: Problem Sorting Partially Filled Arrays
    807599 Newbie
    Currently Being Moderated
    yes, you're right.

    I have been trying to get this to work now:
            //sort the array and show the sorted output
            Arrays.sort(a, 0, numberUsed);
            
            int count;
            
            //show the headers of the columns
            System.out.println("Num" + "  " + "Qty");
            
            //go through the numbers and output them along with their qty
            for (int i = (numberUsed - 1); i >= 0; i--){      
    
              
                count = 0;
                for (int index=0; index < (a.length); index++){
                     if (i == a[index])
              count++;
                }           
                
                if (count > 0)
                System.out.println(i + "\t" + count); 
    
            }
    However, I am now facing the same problem I had before, where it will not display negative numbers that were input and it will "fill" the array with 0's.

    Any suggestions?
  • 11. Re: Problem Sorting Partially Filled Arrays
    807599 Newbie
    Currently Being Moderated
    Do you have to use an array? This would be simpler using a HashMap.
  • 12. Re: Problem Sorting Partially Filled Arrays
    807599 Newbie
    Currently Being Moderated
    Yes, I have to use an array.
  • 13. Re: Problem Sorting Partially Filled Arrays
    807599 Newbie
    Currently Being Moderated
    So I have worked through the 0 issue again and solved that. However, I am now stuck on how to get the program to output the negative numbers that the user has entered. It counts and correctly displays 0 and all positive int's, but not negative int's.
            //go through the numbers and output them along with their qty
            for (int i = (numberUsed - 1); i >= 0; i--){      
    
              
                count = 0;
                for (int index = 0; index < (numberUsed); index++){
                     if (i == a[index])
              count++;
                }                       
                if (count > 0)
                System.out.println(i + "\t" + count); 
            }