Skip to content

Instantly share code, notes, and snippets.

@salluzziluca
Last active July 7, 2022 14:01
Show Gist options
  • Save salluzziluca/b5b8eec377d0050966381535e0041515 to your computer and use it in GitHub Desktop.
Save salluzziluca/b5b8eec377d0050966381535e0041515 to your computer and use it in GitHub Desktop.
Merge Sort
void merge(int *vector1, int cantidad1, int *vector2, int cantidad2, bool ascendente)
{
int vector3[cantidad1 + cantidad2];
int indice1 = 0, indice2 = 0, indice3 = 0;
if(ascendente){
while(indice1 < cantidad1 && indice2 < cantidad2)
{
if(vector1[indice1] < vector2[indice2])
{
vector3[indice3] = vector1[indice1];
indice1++;
}
else
{
vector3[indice3] = vector2[indice2];
indice2++;
}
indice3++;
}
while(indice1 < cantidad1)
{
vector3[indice3] = vector1[indice1];
indice1++;
indice3++;
}
while(indice2 < cantidad2)
{
vector3[indice3] = vector2[indice2];
indice2++;
indice3++;
}
for(int i = 0; i < cantidad1 + cantidad2; i++)
{
vector1[i] = vector3[i];
}
}
else{
while(indice1 < cantidad1 && indice2 < cantidad2)
{
if(vector1[indice1] > vector2[indice2])
{
vector3[indice3] = vector1[indice1];
indice1++;
}
else
{
vector3[indice3] = vector2[indice2];
indice2++;
}
indice3++;
}
while(indice1 < cantidad1)
{
vector3[indice3] = vector1[indice1];
indice1++;
indice3++;
}
while(indice2 < cantidad2)
{
vector3[indice3] = vector2[indice2];
indice2++;
indice3++;
}
for(int i = 0; i < cantidad1 + cantidad2; i++)
{
vector1[i] = vector3[i];
}
}
}
void mergesort(int *vector, int tope, bool ascendente){
if(tope <= 1)
return;
int mitad = tope / 2;
mergesort(vector, mitad, ascendente);
mergesort(vector + mitad, tope - mitad, ascendente);
merge(vector, mitad, vector + mitad, tope - mitad, ascendente);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment