Computer Algorithms II Lecture Notes

23 October 2007 • Assignment 2 Code Review


Outline

The Problem

The Answer

An Observation

A Partial Solution

More Observations

Sorting

unsigned sort(v1[], v2[], v3[], order[])

  return moves(v1, order[0]) +
         moves(v2, order[1]) +
	 moves(v3, order[2])


unsigned moves(v[], mod)

  moves = 0

  for i = 1 to v.size() 
    if v[i] % 3 ≠ mod
      moves++

  return moves

Analysis

Testing

Why Arrays Were Invented

int zeroMod1=0;
int oneMod1=0;
int twoMod1=0;
int zeroMod2=0;
int oneMod2=0;
int twoMod2=0;
int zeroMod3=0;
int oneMod3=0;
int twoMod3=0;

int sumAll=0;
int sumTotalCongruent=0;

int oneSum=0;
int twoSum=0;
int threeSum=0;
int fourSum=0;
int fiveSum=0;
int sixSum=0;

for (j = 0; j < one.size(); j++)
  if (one.at(j) % 3) == 0
    zeroMod1++
  else if (one.at(j) % 3) == 1
    oneMod1++
  else if (one.at(j) % 3) == 2
    twoMod1++

One alternative

unsigned mod1[3]

mod1[0] = mod1[1] = mod1[2] = 0

for (j = 0; j < one.size(); j++)
  mod1[one.at(j) % 3]++


This page last modified on 23 October 2007.

This work's CC license.