Skip to content

Instantly share code, notes, and snippets.

@MrDave1999
Last active July 17, 2019 02:23
Show Gist options
  • Save MrDave1999/03dddf40873816be10ea49352e45e1b3 to your computer and use it in GitHub Desktop.
Save MrDave1999/03dddf40873816be10ea49352e45e1b3 to your computer and use it in GitHub Desktop.
Implementaciones del algoritmo de la burbuja, de una forma eficiente.
#ifndef _BUBBLESORT_H
#define _BUBBLESORT_H
int BubbleSort(int*const parray, const int size)
{
int count; //contar iteraciones.
int total = 0; //total de iteraciones.
int* i;
int* psize = parray + size;
int aux;
unsigned char change = 1;
while(1)
{
count = 0;
for(i = parray + 1; i != psize; ++i)
{
++count;
//Si el elemento siguiente es menor que el elemento anterior...
if(*i < *(i - 1))
{
aux = *(i - 1);
*(i - 1) = *i;
*i = aux;
change = 0;
}
}
total += count;
if(change) break;
change = 1;
--psize;
}
return total;
}
#endif
#ifndef _BUBBLESORT2_H
#define _BUBBLESORT2_H
int BubbleSort2(int* parray, const int size)
{
int count; //contar iteraciones.
int total = 0; //total de iteraciones.
int* i;
int* psize = parray + size;
int aux;
unsigned char //Para ver si hubo intercambio de elementos, con esto sabemos si el arreglo quedó ordenado o no.
change1 = 1,
change2 = 1
;
while(1)
{
count = 0;
change1 = 1;
for(i = parray + 1; i != psize; ++i)
{
++count;
//Si el elemento siguiente es menor que el elemento anterior...
if(*i < *(i - 1))
{
aux = *(i - 1);
*(i - 1) = *i;
*i = aux;
change1 = 0;
}
}
total += count;
if(change1) break;
change2 = 1;
count = 0;
for(i = (--psize) - 1; i != parray; --i)
{
++count;
//Si el elemento siguiente es menor que el elemento anterior...
if(*i < *(i - 1))
{
aux = *(i - 1);
*(i - 1) = *i;
*i = aux;
change2 = 0;
}
}
total += count;
++parray;
if(change2) break;
}
return total;
}
#endif
#include <stdio.h>
#include "bubblesort.h"
#include "bubblesort2.h"
#define MAX_NUM 50
int main(void)
{
srand(time(NULL));
int i;
int num[MAX_NUM];
int num2[MAX_NUM];
for(int i = 0; i != MAX_NUM; ++i)
{
num[i] = rand() % 15;
num2[i] = num[i];
}
printf("(Array 1) Total de iteraciones: %d\n\n", BubbleSort(num, MAX_NUM));
printf("(Array 2) Total de iteraciones: %d\n\n", BubbleSort2(num2, MAX_NUM));
printf("\nArray 1:\n\n");
for(i = 0; i != MAX_NUM; ++i)
printf("%d\n", num[i]);
printf("\nArray 2:\n\n");
for(i = 0; i != MAX_NUM; ++i)
printf("%d\n", num2[i]);
printf("\n");
getchar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment