Foro de elhacker.net

Programación => Programación C/C++ => Mensaje iniciado por: david_BS en 2 Abril 2012, 02:30 am



Título: ejemplo de ordenamientos básicos
Publicado por: david_BS en 2 Abril 2012, 02:30 am

Un par de ejemplos de ordenamientos, uno para enteros que deben ordenarse de menor a mayor, y otro para cadenas que deban ordenarse alfabéticamente.

Código:

//
// UTN FRGP
// 2012
// David_BS
// david_bs@live.com

///////////////////////////////////////////////////

#include <windows.h>
#include <stdio.h>



void TratarVectorDeInt(){//de menor a mayor

printf("\n");

int vec[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };

int aux;

for(int i=0; i< (11-1); i++){

for(int j=(i+1); j< 11; j++){

if(vec[j]<vec[i]){

aux=vec[i];
vec[i]=vec[j];
vec[j]=aux;
}}}

for(int k=0;k<11;k++)
printf("%d\n",vec[k]);

system("pause");
}

int ComparaDosCadenas(const char* str1, const char* str2);

void TratarVectorDeStrings(){//orden alfabético

printf("\n");

char vec[][16] =
{
"Guatemala\0",
"Brasil\0",
"Estados Unidos\0",
"Paraguay\0",
"Argentina\0",
"Chile\0",
"Peru\0",
"Mexico\0",
"Cuba\0",
"Honduras\0"
};

char aux[16];

for(int i=0;i<(10-1);i++){

for(int j=(i+1); j< 10; j++){

if(ComparaDosCadenas(vec[j],vec[i])>0){

   memset(aux,0,sizeof(aux));
   strcpy(aux,vec[i]);
   strcpy(vec[i],vec[j]);
   strcpy(vec[j],aux);
}}}

for(int k=0;k<10;k++)
printf("%s\n",vec[k]);

system("pause");
}



int main()
{

// 1: ordenar un vector de enteros
TratarVectorDeInt();


// 2: ordenar una matriz de char (vector de strings)
TratarVectorDeStrings();

return 0;
}

int ComparaDosCadenas(const char* str1, const char* str2){//si la 1 es menor a la 2

// printf("str1: %s ; str2: %s\n",str1,str2);
int l1=strlen(str1);//brasil
int l2=strlen(str2);//guatemala
char aux1[16];strcpy(aux1,str1);
char aux2[16];strcpy(aux2,str2);
strlwr(aux1);
strlwr(aux2);
// printf("str1: %s ; str2: %s\n",aux1,aux2);

int len=l1;
if(l2<l1) len=l2;

for(int i=0; i<len; i++){

// printf("str1: %c ; str2: %c\n",aux1[i],aux2[i]);

if(aux1[i]<aux2[i]) return 1;
else
if(aux1[i]>aux2[i]) return 0;
}

if(l1>l2) return 1;
return 0;
}

Proyecto
http://www.mediafire.com/?r42y1f6l6yoeju9