Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created April 11, 2020 04:21
Show Gist options
  • Save misterpoloy/1d84e060beb0c97c53765d1b7e4ca480 to your computer and use it in GitHub Desktop.
Save misterpoloy/1d84e060beb0c97c53765d1b7e4ca480 to your computer and use it in GitHub Desktop.
Merge Sort in cpp
#include <iostream>
// Arreglo final
// Arreglo izquierdo
// Arreglo derecho
// tamaño del arreglo izquierdo
// tamaño del arreglo derecho
void Merge(int* A, int* L, int lefCount, int* R, int rightCount) {
int i, leftIndex, rightIndex;
i = 0; leftIndex = 0; rightIndex = 0;
// Agrega los números de menor valor
while (leftIndex < lefCount && rightIndex < rightCount) {
if (L[leftIndex] < R[rightIndex]) {
// Si el menor es menor, agrega el menor
A[i] = L[leftIndex];
leftIndex++;
} else {
// Sino, el derecho es menor y lo agrega
A[i] = R[rightIndex];
rightIndex++;
}
i++;
}
// Llenar los que sobrarón comenzando con izquierda
// Probar con el ejemplo 1, 2, 4, 8 y 3, 5, 7, 6
while (leftIndex < lefCount) {
A[i] = L[leftIndex];
leftIndex++;
i++;
}
// Llenar los que sobrarón comenzando con derecha
while (rightIndex < rightCount) {
A[i] = R[rightIndex];
rightIndex++;
i++;
}
}
void MergeSort(int* A, int length) {
// Base condition
if (length < 2) return;
int half = length/2;
int* left = new int[sizeof(int) * half]; // int rigt[half];
int* right = new int[sizeof(int) * half]; // int rigt[right];
for (int i = 0; i < half; i++) { // populating left subarray
left[i] = A[i];
}
for (int i = half; i < length; i++) { // populating right array
right[i - half] = A[i];
}
MergeSort(left, half);
MergeSort(right, length - half);
Merge(A, left, half, right, length - half);
delete[] left;
delete[] right;
}
int main() {
int A[] = { 2, 4, 1, 6, 8, 5, 3, 7 };
int length = sizeof(A) / sizeof(int);
MergeSort(A, length);
for (int n: A) {
std::cout << n << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment