Codes - Sorting

# Codes - Sorting - #define merge Merge #define swap Swap /*...

This preview shows pages 1–4. Sign up to view the full content.

#define merge Merge #define swap Swap /** * Several sorting routines. * Arrays are rearranged with smallest item first. */ #include "vector.h" // Bubble Sort Function for Descending Order void bubble_sort(apvector <int> &array) { int i, j, flag = 1; // set flag to 1 to begin initial pass int temp; // holding variable int arrayLength = array.length( ); for(i = 1; (i <= arrayLength) && flag; i++) { flag = 0; for (j=0; j < (arrayLength -1); j++) { if (array[j+1] > array[j]) // ascending order simply changes to < { temp = array[j]; // swap elements array[j] = array[j+1]; array[j+1] = temp; flag = 1; // indicates that a swap occurred. } } } return; //arrays are passed to functions by address; nothing is returned }

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
/** * Simple insertion sort. */ template <class Comparable> void insertionSort( vector<Comparable> & a ) { /* 1*/ for( int p = 1; p < a.size( ); p++ ) { /* 2*/ Comparable tmp = a[ p ]; int j; /* 3*/ for( j = p; j > 0 && tmp < a[ j - 1 ]; j-- ) /* 4*/ a[ j ] = a[ j - 1 ]; /* 5*/ a[ j ] = tmp; } } /** * Shellsort, using Shell's (poor) increments. */ template <class Comparable> void shellsort( vector<Comparable> & a ) { for( int gap = a.size( ) / 2; gap > 0; gap /= 2 ) for( int i = gap; i < a.size( ); i++ ) {
Comparable tmp = a[ i ]; int j = i; for( ; j >= gap && tmp < a[ j - gap ]; j -= gap ) a[ j ] = a[ j - gap ]; a[ j ] = tmp; } } /** * Mergesort algorithm (driver). */ template <class Comparable>

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 12/28/2010 for the course CSC CSC1110 taught by Professor Cjyuan during the Fall '06 term at CUHK.

### Page1 / 10

Codes - Sorting - #define merge Merge #define swap Swap /*...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online