/* BEGIN TEMPLATE */ void insertionSort() { /* BEGIN SOLUTION */ int i; for (i = 1; i < getValueCount(); i++) { int value = getValue(i); int j = i; while ((j > 0) && (!isSmallerThan(j-1,value))) { copy(j-1,j); j--; } setValue(j,value); } /* END SOLUTION */ }
/** * Adds a movie in the correct order of a list using recursion. * Creates a new head if necessary. * * precondition: none * * param: movie - the movie to insert * param: head - the head of the list to insert into * param: method - the method of sorting (BY_TITLE, BY_LENGTH, BY_RATING) * param: size - the size of the list. */ void model::InterlacedMovieList::addToList(MovieNode* movie, MovieNode* head, const string& method, int size) { if (size == 1) { int result = compareMovies(head, movie, method); if (result > 0 && this->size == 1) { replaceHead(head, movie, method); return; } else { insertAfter(head, movie, method); return; } } else { MovieNode* next; if (method.compare(BY_TITLE) == 0) { next = head->getNextTitle(); } else if (method.compare(BY_LENGTH) == 0) { next = head->getNextLength(); } else { next = head->getNextRating(); } int comparedToHead = compareMovies(movie, head, method); int comparedToNext = compareMovies(movie, next, method); if (size == this->size && comparedToHead == -1) { insertAfter(head, movie, method); } if (isEqualTo(comparedToHead) || (isSmallerThan(comparedToHead) && isBiggerThan(comparedToNext))) { insertAfter(head, movie, method); return; } else { addToList(movie, next, method, (size - 1)); return; } } }