Connecting Tech Pros Worldwide Forums | Help | Site Map

dropping lowest value after an ascending sort

sonic's Avatar
Member
 
Join Date: Nov 2006
Location: Bloomington, IN
Posts: 40
#1: Feb 6 '07
Does anyone know what I can do to this function to get it to drop the lowest value? Thanks for any insight.

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. void sort(double* score, int size)
  4. {
  5.     int startScan;
  6.     int minIndex;
  7.     double minValue;
  8.  
  9.     for (startScan = 0; startScan < (size - 1); startScan++)
  10.     {
  11.         minIndex = startScan;
  12.         minValue = score[startScan];
  13.         for (int index = startScan + 1; index < size; index++)
  14.         {
  15.             if (score[index] < minValue)
  16.             {
  17.                 minValue = score[index];
  18.                 minIndex = index;
  19.             }
  20.         }
  21.         score[minIndex] = score[startScan];
  22.         score[startScan] = minValue;
  23.     }
  24. }
  25.  
  26.  

Expert
 
Join Date: Nov 2006
Location: UK
Posts: 1,320
#2: Feb 6 '07

re: dropping lowest value after an ascending sort


at the end of your sort you could shuffle the elements down one to remove the minimum value, e.g.
Expand|Select|Wrap|Line Numbers
  1.     for (startScan = 0; startScan < (size - 1); startScan++)
  2.         score[startScan]=score[startScan+1];
  3.     score[size-1]=0;
  4.  
you have to decide what you will put at the end to replace the last element moved, in this case I put a 0
Ganon11's Avatar
Moderator
 
Join Date: Oct 2006
Location: New York, United States of America
Posts: 3,428
#3: Feb 6 '07

re: dropping lowest value after an ascending sort


Since you are sorting from lowest to highest, after you are finished the sort, increment the pointer by one value. This will leave the lowest value in memory (in the location just before the current pointer), but the array will now start with the second lowest value. If you want to avoid memory leak, you can define a new pointer pointing to the same value as the original pointer, increment the original pointer, and then delete the value stored in the new pointer.
Reply