Trying to sort an array of objects

• 05-04-2013, 03:58 PM
superhaNds
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:

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. :)
• 05-04-2013, 04:32 PM
JosAH
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.:

Code:

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

Jos
• 05-04-2013, 05:11 PM
superhaNds
Re: Trying to sort an array of objects
aah yes, otherwise NullPointer..
thanks.