Advanced Placement Computer Science AB:
Quiz 7:  Sorting, Part 1 (n2 Sorts and MergeSort)
   Sewickley Academy, 2000-2001

See Course Home Page.

This is a programming quiz.  You must use Visual C++.  You may not use any notes and you may not start from a preexisting VC++ project (you must only use newly-created files in a newly-created project).

Write insertionSort, bubbleSort, and mergeSort in the following program:

#include <stdio.h>
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
#include "apvector.h"

const int BIG_NUM = 500;

typedef apvector<int> intVector;
typedef intVector& intVectorByReference;

// loadVector() loads the vector v with
// random elements between 0 and BIG_NUM

void loadVector(intVectorByReference v)
{
 // load vector with numbers mostly random in [0,BIG_NUM]
 int i, len;
 len = v.length();
 for (i=0;i<len;i++)
   // not perfect, but good enough selector in [0,BIG_NUM]
   v[i] = rand() * BIG_NUM / RAND_MAX;
}
 

void printVector(intVectorByReference v)
{
 // print vector elements separated by two spaces with
 // a carriage return at the end
  int i, len;
  len = v.length();
  for (i=0;i<len;i++)
    cout << v[i] << "  ";
  cout << endl;
}

void insertionSort(intVector& v)
{
// YOU WRITE THIS, PART 1 of 3
}

void bubbleSort(intVector& v)
{
// YOU WRITE THIS, PART 2 of 3
}

void mergeSort(intVector& v,int lo,int hi)
{
// YOU WRITE THIS, PART 3 of 3
}

void mergeSort(intVector& v)
{
    mergeSort(v,0,v.length()-1);
}

void testSortFunction(char* name,void(*sortFn)(intVector&v),intVector& v)
{
    intVector v2;
 int time1,time2;
    v2 = v;
 cout << "Starting " << name << endl;
 time1 = time(NULL);
    sortFn(v2);
 time2 = time(NULL);
 cout << "Sort took: " << (time2 - time1) << " seconds" << endl;
}

void main()
{
    intVector v;
    int vSize;

    while (true)
    {
        cout << "Enter size of vector (<0 to exit): ";
        cin >> vSize;
        if (vSize < 0)
            return;
        v.resize(vSize);
        loadVector(v);
        // printVector(v);
        testSortFunction("insertionSort",insertionSort,v);
        testSortFunction("bubbleSort",bubbleSort,v);
        testSortFunction("mergeSort",mergeSort,v);
    }
}



See Course Home Page.