Homework Assignment #6
driver.cpp
#include <cstdlib> #include <iostream> #include <sstream> #include <time.h> #include "randSearch.h" using namespace std; void generate (int* a, int n) { a[0] = rand() % 4; for (int i = 1; i < n; ++i) { a[i] = a[i-1] + 1 + rand() % 4; } } int main(int argc, char** argv) { if (argc != 3) { cerr << "When you run this program, you must supply two parameters.\n" << "The first is the size of the arrays you want to generate.\n" << "The second is the number of trials you want to perform.\n" << "\n" << "For example, if you called this program driver, you\n" << "might invoke it as:\n" << " driver 100 10 \n" << "to generate 10 random trials on arrays of 100 elements each." << endl; return 1; } int N; int trials; { istringstream arg1 (argv[1]); arg1 >> N; istringstream arg2 (argv[2]); arg2 >> trials; } srand(time(0)); int *array = new int[N]; // O(1) generate (array, N); // O(N) for (int t = 0; t < trials; t++) // total: O(trials*f(N)) { // where f(N) is the complexity of randSearch int i = rand() % N; // randomly select one element to search for: O(1) randSearch (array, array+N, array[i]); } return 0; }
randSearch.h
/* * randSearch.h * * Created on: Jun 6, 2018 * Author: zeil */ #include <cstdlib> /** * Performs the standard binary search using two comparisons per level. * Returns index where item is found or or the index where it chould * be inserted if not found */ template <typename RandomAccessIterator, typename Value> RandomAccessIterator randSearch (RandomAccessIterator start, RandomAccessIterator stop, const Value& key) { auto low = 0; auto high = stop - start - 1; while( low <= high ) { auto selected = low + rand() % ( high - low + 1); RandomAccessIterator selectedPos = start + selected; if( *selectedPos < key ) low = selected + 1; else if( key < *selectedPos ) high = selected - 1; else return selectedPos; // Found } return start + low; }
makefile
DIR=${PWD} ASST=$(notdir ${DIR}) MAINPROG=driver ifneq (,$(findstring MinGW,$(PATH))) DISTR=MinGW EXE=.exe LFLAGS= else DISTR=Unix EXE= LFLAGS= endif # ######################################################################## # Macro definitions for "standard" C and C++ compilations # CPPFLAGS=-g -std=c++11 CFLAGS=-g TARGET=$(MAINPROG)$(EXE) CPPS=driver.cpp LINK=g++ $(CPPFLAGS) # CC=gcc CXX=g++ # # # In most cases, you should not change anything below this line. # # The following is "boilerplate" to set up the standard compilation # commands: # OBJS=$(CPPS:%.cpp=%.o) DEPENDENCIES = $(CPPS:%.cpp=%.d) %.d: %.cpp touch $@ %.o: %.cpp $(CXX) $(CPPFLAGS) -MMD -o $@ -c $*.cpp # # Targets: # all: $(TARGET) $(TARGET): $(OBJS) $(LINK) $(FLAGS) -o $(TARGET) $(OBJS) $(LFLAGS) clean: -/bin/rm -f *.d *.o $(TARGET) make.dep: $(DEPENDENCIES) -cat $(DEPENDENCIES) > $@ include make.dep