3

I have an array that I want to sort in ascending order. However, I want to sort them with reference to a boolean array.I would like to sort the values that are true in ascending order, followed by the values that are false in ascending order. Little stuck on how to get there.

This is what I have currently:

Object[] arr = new Object[6];

arr[0] = new Object(2); 
arr[1] = new Object(5); 
arr[2] = new Object(3); 
arr[3] = new Object(1);
arr[4] = new Object(6);
arr[5] = new Object(4);

Available[] avalarr = new Available[6];

availarr[0] = new Available (true);
availarr[1] = new Available (false);
availarr[2] = new Available (false);
availarr[3] = new Available (true);
availarr[4] = new Available (true);
availarr[5] = new Available (false);

I need the output to be:

1 2 6 3 4 5

6
  • First, get both "newAvailable" and your object into a single thing to be compared, e.g. define a new object containing an instance of both. Then, implement a custom comparator (docs.oracle.com/javase/7/docs/api/index.html?java/util/…). Your "compare" method should always first check the boolean values of your new object--then the integer value. Finally, use Arrays.sort with your new single array and your new comparator. Commented Jun 2, 2015 at 0:27
  • ...though I'm not sure what you mean by "new Object(2);". I assumed you had a class, say "Thing", that took an integer constructor: class Thing { public Thing(int value){ this.value = value; } }. Right? Commented Jun 2, 2015 at 0:31
  • Thanks for your response it is much appreciated. I will test and see how it goes.Yes you are correct on the variables Commented Jun 2, 2015 at 0:38
  • Do you have 2 arrays? Or 1 array with filled with a class that has two attributes (1 integer, and 1 boolean)? Commented Jun 2, 2015 at 0:57
  • Currently i have 2 arrays. Commented Jun 2, 2015 at 1:15

2 Answers 2

1

Code:

import java.util.Arrays;

public class SelectiveSort {

    public static void main(String[] args) {

        Item [] items = new Item [6];
        items[0] = new Item(2, true);
        items[1] = new Item(5, false);
        items[2] = new Item(3, false);
        items[3] = new Item(1, true);
        items[4] = new Item(6, true);
        items[5] = new Item(4, false);

        System.out.println("Before Sorting:");
        // Removed enhanced for loop
        for(int i = 0; i < items.length; i++) {
            System.out.print(items[i].getIntValue() + " ");
        }

        // Sorting
        Arrays.sort(items);

        System.out.println("\n\nAfter Sorting:");
        // Removed enhanced for loop
        for(int i = 0; i < items.length; i++) {
            System.out.print(items[i].getIntValue() + " ");
        }
        System.out.println();
    }
}

class Item implements Comparable<Item> {

    private int _intValue;
    private boolean _boolValue;

    public Item(int intValue, boolean boolValue) {
        _intValue = intValue;
        _boolValue = boolValue;
    }

    public int getIntValue() { return _intValue; }

    public boolean getBoolValue() { return _boolValue; }

    @Override
    public int compareTo(Item otherItem) {

        // Using explicit comparison
        int boolComparison = (_boolValue == otherItem._boolValue) ? 0 :
            (_boolValue) ? 1 : -1;
        return (boolComparison != 0) ? -boolComparison :
            ( (_intValue == otherItem.getIntValue()) ? 0 :
                (_intValue > otherItem.getIntValue()) ? 1 : -1);
    }
}

Output:

Before Sorting: 2 5 3 1 6 4

After Sorting: 1 2 6 3 4 5


Explanation:

The idea is to let your "Item" implement Comparable, and override the compareTo(Item otherItem) function based on the desired order.
Once that is done, all you need to do is to call Arrays.sort() on your array of Item.

Version 2 (w/o Comparable/Comparator):

public class SelectiveSort {

    public static void main(String[] args) {

        Item [] items = new Item [6];
        items[0] = new Item(2, true);
        items[1] = new Item(5, false);
        items[2] = new Item(3, false);
        items[3] = new Item(1, true);
        items[4] = new Item(6, true);
        items[5] = new Item(4, false);

        System.out.println("Before Sorting:");
        for(int i = 0; i < items.length; i++) {
            System.out.print(items[i].getIntValue() + " ");
        }

        // Sorting
        bubbleSort(items);

        System.out.println("\n\nAfter Sorting:");
        for(int i = 0; i < items.length; i++) {
            System.out.print(items[i].getIntValue() + " ");
        }
        System.out.println();
    }

    public static void bubbleSort(Item [] items) {
        int n = items.length;
        do {
            int newN = 0;
            for(int i = 1; i < n; i++) {
                if(compareTo(items[i-1], items[i]) == 1) {
                    Item temp = items[i-1];
                    items[i-1] = items[i];
                    items[i] = temp;

                    newN = i;
                }
            }
            n = newN;
        } while (n != 0);
    }

    public static int compareTo(Item item1, Item item2) {

        int boolComparison = (item1.getBoolValue() == item2.getBoolValue())
                ? 0 : (item1.getBoolValue()) ? 1 : -1;
        return (boolComparison != 0) ? -boolComparison :
            ( (item1.getIntValue() == item2.getIntValue()) ? 0 :
                (item1.getIntValue() > item2.getIntValue()) ? 1 : -1);
    }
}
Sign up to request clarification or add additional context in comments.

16 Comments

Thank for your assistance Guys, i generally get it.. As i said i am quite new to all this. I get a error come up when i compile the project. Any ideas? Cheers Semantic Error: Enhanced for loops (also known as foreach loops) are only supported for `-source 1.5' or greater.
Updated my answer, changed the 'enhanced for loop' to a 'normal for loop'.
Cheers. One error solved another one appeared??. Exception in thread "main" java.lang.Error: Unresolved compilation problems: The method compare(boolean, boolean) is undefined for the type Boolean The method compare(int, int) is undefined for the type Integer
It has to do with the Java version you are using. Anyway, updated answer. Changes are in the compareTo function.
Thank you for your assistance it is greatly appreciated. Works perfect. As i am reasonably new to all this is there any particular literature or courses that you would recommend? thanks again.
|
0

(To expand on my comment:

You need a basic "thing":

class Thing {
   boolean newAvailable;
   int order;
   public Thing(boolean newAvailable, int order) {
      ...
   }
}

...and a Comparable...

class CompareThings implements Comparator<Thing> {
    ...
    int compare(Thing t1, Thing t2) {
        if (t1.newAvailable!=t2.newAvailable)
            return t1.newAvailable==true ? 1 : -1;
        return t1.order-t2.order;
    }
}

(Note that t1.newAvailable==true is redundant, but I think it clarifies what's going on here.)

Now build an array of Thing and call Arrays.sort(Thing[] things, CompareThings);

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.