Introduction to Computer Science:
Solutions to Quiz 4
    Sewickley Academy, 2000-2001

See Course Home Page.

The following is the complete solution to Quiz 4.   The bold portions are where you should have written or modified code.



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

const int SIZE = 12;

void loadVector(apvector<int>& v)
{
 int i, seed;
 const int NUM1 = 12353;
 const int NUM2 = 1053;

 cout << "Enter a seed to load the vector: ";
 cin >> seed;

 i = 0;
 while (i < SIZE)
 {
  v[i] = (-1 + 2 * (i % 2)) * seed;
  seed = (seed * NUM1) % NUM2;
  i = i + 1;
 }
}

int findIndexOfMaxRemainingValue(apvector<int>& v, int startIndex)
{
 int i, max, maxIndex;

 max = v[startIndex];
 maxIndex = startIndex;
 i = startIndex;

 while (i < SIZE)
 {
  if (v[i] > max)
  {
   max = v[i];
   maxIndex = i;
  }
  i = i + 1;
 }
 return maxIndex;
}

void swapValues(apvector<int>& v, int index1, int index2)
{
 int temp;

 temp = v[index1];
 v[index1] = v[index2];
 v[index2] = temp;
}

void sortVector(apvector<int>& v)
{
 int i, maxIndex;

 i = 0;
 while (i < SIZE)
 {
  maxIndex = findIndexOfMaxRemainingValue(v,i);
  swapValues(v,i,maxIndex);
  i = i + 1;
 }
}

void printVector(apvector<int>& v)
{
 int i;

 cout << "Vector = ";
 i = 0;
 while (i < SIZE)
 {
  cout << v[i];
  if (i < SIZE-1)
  {
   cout << ", ";
  }
  i = i + 1;
 }
 cout << endl << endl;
}

// Consider that median = (v[(SIZE-1)/2] + v[SIZE/2])/2;
// If SIZE is odd:
//    If SIZE = 3, median = v[1] = (v[1] + v[1])/2
//    If SIZE = 5, median = v[2] = (v[2] + v[2])/2
// If SIZE is even:
//    If SIZE = 2, median = (v[0] + v[1]) / 2
//    If SIZE = 4, median = (v[1] + v[2]) / 2
//    If SIZE = 6, median = (v[2] + v[3]) / 2
void printMedian(apvector<int>& v)
{
 double median;
 median = (v[(SIZE-1)/2] + v[SIZE/2]) / 2.0;
 cout << "Median = " << median << endl;
}

void main()
{
 apvector<int> v(SIZE);

 loadVector(v);
 printVector(v);
 sortVector(v);
 printVector(v);
 printMedian(v);
 getchar();
}


See Course Home Page.