问题描述:

This following of my program should recieve an array of objects and sort them based on the size of their privilege variable. The "arrayFromBefore" variable is filled with objects of type MyClass. It just basically creates a new MyClass object and returns it with the same attributes of the object.

The problem is, in certain cases, there seems to be several occurences of the same MyClass object in the priority array. These duplications are also not always the same multiple (e.g. one object occurs 3 times in a row, another 5 times in a row, another twice, etc...)

MyClass[] priorityArray = new MyClass[arrayFromBefore.length];

for (int i = 0; i < priorityArray.length; i++) {

int maxIndex = 0;

int maxPrivilege = arrayFromBefore[i].returnPrivilege();

for (int j = 1; j < arrayFromBefore.length; j++) {

int currentPrivilege = arrayFromBefore[j].returnPrivilege();

if (currentPrivilege > maxPrivilege) {

maxPrivilege = currentPrivilege;

maxIndex = j;

}

}

MyClass mostPrivilaged = arrayFromBefore[maxIndex];

priorityArray[i] = mostPrivileged;

arrayFromBefore[maxIndex].setPriority(-900000000);

}

网友答案:

The problem is in your inner for-loop where for each i, j starts from same value 1. j should start exactly from next to i, so that same object cannot be overrided.

MyClass[] priorityArray = new MyClass[arrayFromBefore.length];
   for (int i=0; i<priorityArray.length - 1; i++) {
   int maxIndex = 0;
   int maxPrivilege = arrayFromBefore[i].returnPrivilege();
   for (int j=1+i; j<arrayFromBefore.legnth; j++) {
       int currentPrivilege = arrayFromBefore[j].returnPrivilege();
       if (currentPrivilege > maxPrivilege) {
           maxPrivilege = currentPrivilege;
           maxIndex = j;
       }
   }

// priorityArray[i] = mostPrivileged;  this line can be removed as it isn't required because you are getting sorted arrayFromBefore.  

myClass mostPrivilaged = arrayFromBefore[maxIndex];   // Swapping of        
arrayFromBefore[maxIndex] = arrayFromBefore[i];       // largest priority object
arrayFromBefore[i] = mostPrivilaged;                  // with its required position in sorted array.

}

After this you will get arrayFromBefore as shorted in descending order of priority.

相关阅读:
Top