Please use the [ CODE ] ... [ /CODE ] tags (remove spaces) or use the button below the edit box to preserve your code's formatting so it's more readable.
When you create an array of objects, all the elements are initialized to null, so you must assign valid object references to them before accessing them.Also, in Java the standard is for classes to use CamelCase, methods and variables to use camelCase (first letter lowercase), and constants to use ALL_CAPS with underscores to separate words. For example, p.setData(...).
Can you post the class that contains the sort(Person) method and the code that calls it? If you provide more context, we'll have a chance at helping you. Make sure you use the CODE tags I described, please.Does Question6 extend the Person class? What are you trying to do at this line?
This method requires an array of ints, not Persons. You can change it to "Person a", but then the other line I quoted won't compile because Java cant use > to compare objects -- only primitives (int, char, float).
Look up the java.util.Comparable interface in the JavaDocs for the standard way of comparing objects. It defines a single method that you can implement: [ February 23, 2005: Message edited by: David Harkness ]
On a side note, your bubble sort algorithm is doing some wasted work (will never have an effect). For example, consider this list of integers:The first time through the outer loop (i = 0), the first element is compared to every element (including itself) and swapped if the other element is smaller.It's trivial compared to all the comparisons being done, but comparing an element to itself will always fail the test, so it's wasted effort.
But more importantly, what do we know about element 0 at this point? It's the smallest value in the list and therefore will never be swapped again. Yet it will continue to be compared each time through the loop.
So on the first loop we know that you only need to compare element 0 to elements 1, 2, and 3. On the second loop, you must compare element 1 to only 2 and 3. Can you generalize this pattern?