I am working on an implementation of merge-sort which will sort a list of songs by their length. I have written the following and have been unable to fins the flaw in my logic. Instead of returning a sorted list these functions return a list of one item from the middle of the original list.
vector<song> merge( vector<song> firstList, vector<song> secondList){
vector<song> outPut;
int i = 0; int n = 0;
while( outPut.size() < (firstList.size() + secondList.size()-1 )){
if( firstList[i].length < secondList[n].length){
outPut.push_back( firstList[i]);
i++;
}else{
outPut.push_back( secondList[n]);
n++;
}
}
return outPut;
}
vector<song> mergeSortLength( vector<song> playlist){
int scope = playlist.size()/2;
vector<song> firstHalf( &playlist[0], &playlist[scope]);
vector<song> secondHalf( &playlist[scope], &playlist[playlist.size()]);
if ( firstHalf.size() != 1){
firstHalf = mergeSortLength(firstHalf);
}
if ( secondHalf.size() != 1){
secondHalf = mergeSortLength( secondHalf);
}
return merge( firstHalf, secondHalf);
}
If I change the while loop condition from
( outPut.size() < (firstList.size() + secondList.size() -1)){
to
( outPut.size() < (firstList.size() + secondList.size())){
it gets about halfway though the list sorting successfully until the compiler spits out:
playList(27898,0x7fff78b7b000) malloc: * mach_vm_map(size=7526769998340063232) failed (error code=3) * error: can't allocate region *** set a breakpoint in malloc_error_break to debug libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc Abort trap: 6
I really appreciate anyones help. My eyes are going fuzzy from staring at this.