Skip to content

Instantly share code, notes, and snippets.

@namhyun-gu
Last active April 15, 2019 19:46
Show Gist options
  • Save namhyun-gu/c4a68efc8f6eabc4acc9 to your computer and use it in GitHub Desktop.
Save namhyun-gu/c4a68efc8f6eabc4acc9 to your computer and use it in GitHub Desktop.
Merge Sort (merge)
/*
Merge array
@param f_s : first_start
@param f_e : first_end
@param s_s : second_start
@param s_e : second_end
@param source : source array
*/
void merge(int f_s, int f_e, int s_s, int s_e, int* source) {
int size = (s_e - f_s) + 1; // Merged array capacity
int* temp = new int[size];
int temp_index, first_index, second_index;
for (temp_index = 0, first_index = f_s, second_index = s_s;
first_index <= f_e && second_index <= s_e;) {
if (source[first_index] < source[second_index]) {
temp[temp_index] = source[first_index];
first_index++;
} else {
temp[temp_index] = source[second_index];
second_index++;
}
temp_index++; // Pointed next array index
}
while (first_index <= f_e) {
temp[temp_index] = source[first_index];
first_index++;
temp_index++;
}
while (second_index <= s_e) {
temp[temp_index] = source[second_index];
second_index++;
temp_index++;
}
for (int source_index = f_s, temp_index = 0; source_index <= s_e;
source_index++, temp_index++) {
source[source_index] = temp[temp_index];
}
delete[] temp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment