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).

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.

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern