Results 1 to 3 of 3
  1. #1
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    262
    Rep Power
    2

    Default Trying to sort an array of objects

    Hey, I have an array of objects and I want to sort them by their priority. Priority is from 1 to 5 and I use the same approach as a bubble sort since it is the same concept

    code:

    Java Code:
    public void sortTasksByPriority() {
    	for (int k = 0; k < tasks.length - 1; k++) {
    	    boolean isSorted = true;
    	    for (int j = 1; j < tasks.length - 1; j++) {
    		if ((tasks[j].getPriority() < tasks[j - 1].getPriority()) && (tasks[j] != null 
    			&& tasks[j - 1] != null)) {
    		    Task tempTask = tasks[j];
    		    tasks[j] = tasks[j - 1];
    		    tasks[j - 1] = tempTask;
    		    isSorted = false;
    		}
    		    
    	    }
    	    if (isSorted) {
    		break;
    	    }
    	}
        }
    getPriority() returns an integer from 1 to 5.
    Can it be done this way? point me to any logic errors and inform me of a better way to accomplish this. :)

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,336
    Blog Entries
    7
    Rep Power
    20

    Default Re: Trying to sort an array of objects

    If task j-1 and/or task j can be null, better test that before you ask for their priority, i.e.:

    Java Code:
    		if ((task[j-1] != null && task[j] != null && task[j].getPriority() < tasks[j - 1].getPriority()) {
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    262
    Rep Power
    2

    Default Re: Trying to sort an array of objects

    aah yes, otherwise NullPointer..
    thanks.

Similar Threads

  1. Sort ArrayList of different objects
    By jahshuwuh in forum New To Java
    Replies: 7
    Last Post: 04-15-2013, 04:42 AM
  2. Bubble Sort objects
    By dougie1809 in forum New To Java
    Replies: 23
    Last Post: 03-26-2012, 12:19 AM
  3. Replies: 0
    Last Post: 10-04-2011, 10:45 PM
  4. How to sort array objects into alphabetical order...
    By lisalala in forum New To Java
    Replies: 5
    Last Post: 03-03-2009, 11:01 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •