TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: ALL
from: DAVID NOON
date: 1998-04-18 18:03:00
subject: Selection Sort, Mk. Ii

Hi All,
After a suggestion by George White, I have modified the template I posted
for Selection sort a week or two ago. The change is to anchor the
comparisons at the right-most end and work downwards. This will produce a
slightly shorter loop on the Intel platform. Mileage will vary on other
hardware platforms.
I also changed the "current extremum" placeholder from a subscript to a
pointer. This will produce better code from 16-bit compilers, and some
32-bit compilers, on the Intel platform. Again, mileage can vary on other
hardware platforms.
============================= selectn.hpp ==================================
// Templates for Selection sort algorithm for ascending & descending sort.
// Copyright (C) 1998, David W. Noon
// All rights reserved.
// You may use this code freely. You may also distribute it, provided
// no charge is levied beyond that for its distribution medium.
// The author makes no warranty of the code's usefulness for any purpose,
// and accepts no responsibility for any damages caused by its misuse.
template void ascending(T array[], int n)
{
   int i, j;
   T Hold_it_here;
   T * m;
   for (i = n - 1; i > 0; --i)
   {
      m = &array[i]; // Assume rightmost is maximum
      // Scan for true maximum
      for (j = i - 1; j >= 0; --j)
         if (array[j] > *m)
            m = &array[j];
      // Exchange maximum with rightmost
      Hold_it_here = *m;
      *m = array[i];
      array[i] = Hold_it_here;
   }
}
template void descending(T array[], int n)
{
   int i, j;
   T Hold_it_here;
   T * m;
   for (i = n - 1; i > 0; --i)
   {
      m = &array[i]; // Assume rightmost is minimum
      // Scan for true minimum
      for (j = i - 1; j >= 0; --j)
         if (array[j] < *m)
            m = &array[j];
      // Exchange minimum with rightmost
      Hold_it_here = *m;
      *m = array[i];
      array[i] = Hold_it_here;
   }
}
============================================================================
Still not a speed burner, as I said before. However, it is useful for
sorting structures with a simple sort key (e.g. an int) and with a lot of
data to shift on each exchange, i.e. when the cost of a comparison is much
less than the cost of an exchange.
Regards
Dave

___
 * MR/2 2.25 #353 * Psychoceramics: The study of crackpots.
--- Maximus/2 3.01
---------------
* Origin: DoNoR/2,Woking UK (44-1483-717905) (2:440/4)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.