00001 #ifndef SHELL_SORT_CLASS 00002 #define SHELL_SORT_CLASS 00003 00004 /*****************************************************************************\ 00005 * * 00006 * Name : shell_sort * 00007 * Author : Chris Koeritz * 00008 * * 00009 ******************************************************************************* 00010 * Copyright (c) 1991-$now By Author. This program is free software; you can * 00011 * redistribute it and/or modify it under the terms of the GNU General Public * 00012 * License as published by the Free Software Foundation; either version 2 of * 00013 * the License or (at your option) any later version. This is online at: * 00014 * http://www.fsf.org/copyleft/gpl.html * 00015 * Please send any updates to: fred@gruntose.com * 00016 \*****************************************************************************/ 00017 00018 #include "definitions.h" 00019 00021 00027 template <class type> 00028 void shell_sort(type v[], int n, bool reverse = false) 00030 00032 { 00033 type temp; 00034 int gap, i, j; 00035 // the gap sizes decrease quadratically(?). they partition the array of 00036 // items that need to be sorted into first two groups, then four, then 00037 // eight, .... 00038 // within each gap's worth of the array, the next loop takes effect... 00039 for (gap = n / 2; gap > 0; gap /= 2) { 00040 // the i indexed loop is the base for where the comparisons are made in 00041 // the j indexed loop. it makes sure that each item past the edge of 00042 // the gap sized partition gets considered. 00043 for (i = gap; i < n; i++) { 00044 // the j indexed loop looks at the values in our current gap and ensures 00045 // that they are in sorted order. 00046 if (!reverse) { 00047 // normal ordering. 00048 for (j = i - gap; j >= 0 && v[j] > v[j + gap]; j = j - gap) { 00049 // swap the elements that are disordered. 00050 temp = v[j]; 00051 v[j] = v[j + gap]; 00052 v[j + gap] = temp; 00053 } 00054 } else { 00055 // reversed ordering. 00056 for (j = i - gap; j >= 0 && v[j] < v[j + gap]; j = j - gap) { 00057 // swap the elements that are disordered. 00058 temp = v[j]; 00059 v[j] = v[j + gap]; 00060 v[j + gap] = temp; 00061 } 00062 } 00063 } 00064 } 00065 } 00066 00067 #endif // outer guard. 00068
1.5.1