Skip to content

Instantly share code, notes, and snippets.

@MrDave1999
Last active July 24, 2019 00:33
Show Gist options
  • Save MrDave1999/31419c8eacc15a45d5be4543ceeb8b68 to your computer and use it in GitHub Desktop.
Save MrDave1999/31419c8eacc15a45d5be4543ceeb8b68 to your computer and use it in GitHub Desktop.
Algoritmo de selección en C
#include <stdio.h>
#define MAX_NUM 50
int SelectionSort(int*const pnum, const int size)
{
int* i = pnum;
int* j;
int* min;
int* psize = pnum + size;
int aux;
unsigned char change = 1;
int count = 0;
int total = 0;
while(1)
{
min = i;
change = 1;
count = 0;
for(j = i + 1; j != psize; ++j)
{
if(*min > *j)
min = j;
if(*j < *(j-1)) //Si el elemento siguiente es menor al anterior, significa que no está ordenado el arreglo.
change = 0;
++count;
}
total += count;
if(i != min)
{
aux = *i;
*i = *min;
*min = aux;
}
++i;
if(change) break;
}
return total;
}
int main(void)
{
srand(time(NULL));
int num[MAX_NUM];
int tot;
for(int i = 0; i != MAX_NUM; ++i)
num[i] = rand() % 100;
tot = SelectionSort(num, MAX_NUM);
for(int i = 0; i != MAX_NUM; ++i)
printf("%d\n", num[i]);
printf("Total iteraciones: %d\n", tot);
getchar();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment