markruff icon

Insertion Sort (template class)

markruff | PRO | 01/05/16 02:42:44 AM UTC | 0 ⭐ | 388 👁️ | Never ⏰ | []
C++ |

1.05 KB

|

None

|

0 👍

/

0 👎

/*
 * insertion sort
 * 
 * insertion sort using template classes
 *
 * Author: Mark Ruff
 */
 
template <class T>
void insertion_sort( T* array, int size ) {
 
  // start at the SECOND element, if we're past the end of the array finish
  for ( int i = 1 ; i < size ; i++ ) {
    T current_value = array[i];
    // compare to all elements prior to the currently selected, starting at the
    // largest (furthest along the array). These will be sorted
    for ( int j = i ; j >= 0  ; j-- ) {
       // if we make it to the start, current must be the smallest element
       if ( j == 0 ) {
         array[j] = current_value;
       }
       // if the current element is smaller than the sorted element, shift
       // the sorted element to the right 
       else if ( current_value < array[j - 1] ) {
         array[j] = array [j - 1];
       // otherwise the current element must be bigger, so slot it in here
       // (any bigger elements have been  moved to the right already)
       }
       else {
         array[j] = current_value;
         break;
       }
    }
  }
}

Comments