HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppMinor

Merge sort with raw C++ array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
mergewitharrayrawsort

Problem

Merge function:

void merge(int outputArray[], int firstArray[], int sizeFirst, int secondArray[], int sizeSecond){
    int p = 0;
    int p1 = 0; 
    int p2 = 0;
    while(p1 < sizeFirst && p2 < sizeSecond){
        if(first[p1] < second[p2])
            outputArray[p++] = firstArray[p1++];
        else 
            outputArray[p++] = secondArray[p2++];
    }

    while(p1 < sizeFirst) outputArray[p++] = firstArray[p1++];
    while(p2 < sizeSecond) outputArray[p++] = secondArray[p2++];
}


Sort function:

void sort(int numbers[], int size){
    if(size == 1) return;
    int mid = size/2;
    int firstPartSize = mid;
    int secondPartSize = size - mid;

    int firstArray[firstPartSize];
    int secondArray[secondPartSize];

    for(int i = 0 ; i < size ;i++){
        if(i < mid)
            firstArray[i] = numbers[i];
        else 
            secondArray[i - mid] = numbers[i];
    }

    sort(firstArray, firstPartSize);
    sort(secondArray, secondPartSize);
    merge(numbers, first, firstPartSize, second, secondPartSize);
}


Personally I think the number of arguments in the merge function are bit too many. I considered making a different function that calculates size of the array but that didn't seem to work with my current knowledge of the language.

  • Should I care about readability in standard algorithms?



  • What other names would you suggest instead of p, p1, p2 so that readability is not hampered?



  • Are there any other bugs or problems with the code?

Solution

With regards to variable names and readability, I would recommend the following:

-
Change p to outputIndex

-
Change p1 to firstIndex

-
Change p2 to secondIndex

-
Change sizeFirst to firstSize

-
Change sizeSecond to secondSize

Context

StackExchange Code Review Q#75123, answer score: 4

Revisions (0)

No revisions yet.