elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: ¿Eres nuevo? ¿Tienes dudas acerca del funcionamiento de la comunidad? Lee las Reglas Generales


  Mostrar Mensajes
Páginas: [1]
1  Programación / Programación Visual Basic / iniciar en visual basic 10 en: 21 Diciembre 2010, 16:22 pm
hola a todos bueno quiero incursionar en el visual basic 10 , estado trabajando muxo tiempo con el devcpp y digamos q eso casi no es nada eh dejado trabajos interesantes en programacion C++ , pero en fin haber si alguien me puede orientar para incursionar y conocer todos los comandos en visual basic 10
2  Programación / Programación C/C++ / Implementaciones Basicas en un Arbol Binario .... en: 14 Diciembre 2010, 22:11 pm
 Arbol Binario Balanceado implementado con el pseudocodigo del libro de Estructura de Datos de Osvaldo Cairo. Les recomiendo ese libro .
Es interesante este algoritmo para los ordenamientos en arboles y busquedas.
 

ATTE : ANTON RAMIREZ , LEONARDO VLADIMIR  (ALUMNO UNI)


Código:
using namespace std;

struct NODO
{
   NODO *izq;
int       info;
NODO *der;
int FE;
};

void InsercionBalanceado(NODO **nodocabeza, bool *BO, int infor);
void Busqueda(NODO *nodo,int infor);
void Preorden(NODO *);
void Inorden(NODO *);
void Postorden(NODO *);
void Restructura1(NODO **nodocabeza, bool *BO);
void Restructura2(NODO **nodocabeza, bool *BO);
void Borra(NODO **aux1, NODO **otro1, bool *BO);
void EliminacionBalanceado(NODO **nodocabeza, bool *BO, int infor);
int Menu();

int main()
{
   int Opcion;
   int elemento;
   NODO *borrado, *raiz;
   raiz=NULL;
   system("cls");
   Opcion = Menu();
   bool inicio;
   while (Opcion)
   {
      system("cls");
switch(Opcion)
      {
         case 1:
            cout<<"\nRUTINA DE INSERCION\n\n";
            cout<<"\nIngrese elemento a insertar: ";
            cin>>elemento;
            inicio=false;
            InsercionBalanceado(&raiz, &inicio, elemento);
            break;

         case 2:
cout<<"\nRUTINA DE BUSQUEDA\n\n";
            cout<<"\nIngrese elemento a buscar: ";
            cin>>elemento;
            Busqueda(raiz, elemento);
            break;
         case 3:
            printf("\nRECORRIDO PREORDEN\n\n");
            printf("\nEl arbol es: \n\n");
         Preorden(raiz);
            printf("\n\n");
            system("pause");
            break;
         case 4:
            printf("\nRECORRIDO INORDEN\n\n");
            printf("\nEl arbol es: \n\n");
Inorden(raiz);
printf("\n\n");
            system("pause");
            break;
         case 5:
            printf("\nRECORRIDO POSTORDEN\n\n");
            printf("\nEl arbol es: \n\n");
            Postorden(raiz);
            printf("\n\n");
            system("pause");
            break;
       case 6:
cout<<"\nRUTINA DE ELIMINACION\n\n";
            cout<<"\nIngrese elemento a eliminar: ";
            cin>>elemento;
            inicio=false;
            EliminacionBalanceado(&raiz, &inicio, elemento);
            break;
         case  0: exit(0);
      }
      Opcion = Menu();
   }
   system("pause");
   return(0);
}
int Menu()
{
   int Op;
   do{
      system("cls");
      cout<<"\n\n\t    ARBOL  BINARIO BALANCEADO \n\n";
      cout<<"\t1) Insertar\n";
cout<<"\t2) Buscar\n";
cout<<"\t3) PreOrden\n";
cout<<"\t4) InOrden\n";
cout<<"\t5) PostOrden\n";
cout<<"\t6) Eliminacion\n";
cout<<"\t0) Salir\n\n";
      printf("Digite su opcion ---> ");
      cin>>Op;
   }while(Op<0 || Op>7);
   return (Op);
}

void InsercionBalanceado(NODO **nodocabeza, bool *BO, int infor)
{
NODO *nodo, *nodo1, *nodo2;
   nodo=*nodocabeza;
   if(nodo!=NULL)
{
if( infor < nodo->info )
{
InsercionBalanceado(&(nodo->izq),BO,infor);
if( *BO == true )
{
switch(nodo->FE)
{
case 1: nodo->FE=0;
*BO=false;
break;
case 0: nodo->FE=-1;
break;
case -1: nodo1=nodo->izq;//reestructuracion del arbol
if (nodo1->FE<=0)
{ //Rotacion II
nodo->izq=nodo1->der;
nodo1->der=nodo;
nodo->FE=0;
nodo=nodo1;
}
else
{ //Rotacion ID
nodo2=nodo1->der;
nodo->izq=nodo2->der;
nodo2->der=nodo;
nodo1->der=nodo2->izq;
nodo2->izq=nodo1;

if (nodo2->FE==-1)
nodo->FE=1;
else
nodo->FE=0;

if (nodo2->FE==1)
nodo1->FE=-1;
else
nodo1->FE=0;
nodo=nodo2;
}
nodo->FE=0;
*BO=false;
break;
}
}
}
else
{
if( infor > nodo->info )
{
InsercionBalanceado(&(nodo->der),BO,infor);
if( *BO == true )
{
switch(nodo->FE)
{
case -1: nodo->FE=0;
*BO=false;
break;
case 0: nodo->FE=1;
break;
case 1: nodo1=nodo->der;//reestructuracion del arbol
if (nodo1->FE>=0)
{ //Rotacion DD
nodo->der=nodo1->izq;
nodo1->izq=nodo;
nodo->FE=0;
nodo=nodo1;
}
else
{ //Rotacion DI
nodo2=nodo1->izq;
nodo->der=nodo2->izq;
nodo2->izq=nodo;
nodo1->izq=nodo2->der;
nodo2->der=nodo1;

if (nodo2->FE==1)
nodo->FE=-1;
else
nodo->FE=0;

if (nodo2->FE==-1)
nodo1->FE=1;
else
nodo1->FE=0;

nodo=nodo2;
}
nodo->FE=0;
*BO=false;
break;
}
}
}
else
{
cout<<"\nEl nodo ya se encuentra en el arbol\n"<<endl;
system("pause");
}
}
}
else
{
//NODO *otro;
      nodo = new(NODO);
      nodo->izq=NULL;
      nodo->der=NULL;
      nodo->info=infor;
      nodo->FE=0;
      *BO=true;
}
   *nodocabeza=nodo;
}

void Busqueda(NODO *nodo,int infor)
{
if(nodo!=NULL)
{
if( infor < nodo->info )
{
Busqueda(nodo->izq,infor);
}
else
{
if( infor > nodo->info )
{
Busqueda(nodo->der,infor);
}
else
{
cout<<"\nEl nodo SI se encuentra en el arbol\n"<<endl;
system("pause");
}
}
}
else
{
cout<<"\nEl nodo NO se encuentra en el arbol\n"<<endl;
system("pause");
}
}

void Preorden(NODO *nodo)
{
if (nodo!=NULL)
{
cout<<nodo->info<<"\t";
Preorden(nodo->izq);
Preorden(nodo->der);
}
}

void Inorden(NODO *nodo)
{
if (nodo!=NULL)
{
Inorden(nodo->izq);
cout<<nodo->info<<"\t";
Inorden(nodo->der);
}
}

void Postorden(NODO *nodo)
{
if (nodo!=NULL)
{
Postorden(nodo->izq);
Postorden(nodo->der);
cout<<nodo->info<<"\t";
}
}

/*void Eliminacion(NODO **nodocabeza, int infor)
{
NODO *nodo, *otro, *aux, *aux1;
   nodo=*nodocabeza;
   if(nodo!=NULL)
{
if( infor < nodo->info )
{
Eliminacion(&(nodo->izq),infor);
}
else
{
if( infor > nodo->info )
{
Eliminacion(&(nodo->der),infor);
}
else
{
otro=nodo;
if (otro->der==NULL)
{
nodo=otro->izq;
}
else
{
if (otro->izq==NULL)
{
nodo=otro->der;
}
else
{
aux=otro->izq;
aux1=aux;
while(aux->der!=NULL)
{
aux1=aux;
aux=aux->der;
}
otro->info=aux->info;
otro=aux;
aux1->der=aux->izq;
}
}
}
}
delete(otro);
}
else
{
cout<<"\nEl nodo NO se encuentra en el arbol\n"<<endl;
system("pause");
}
*nodocabeza=nodo;
}
*/
void Restructura1(NODO **nodocabeza, bool *BO)
{
NODO *nodo, *nodo1, *nodo2;
   nodo=*nodocabeza;
   if ( *BO==true )
   {
switch(nodo->FE){
case -1: nodo->FE=0;
break;
case 0: nodo->FE=1;
*BO=false;
break;
case 1: //reestructuracion del arbol
nodo1=nodo->der;
if(nodo1->FE>=0){ //rotacion DD
nodo->der=nodo1->izq;
nodo1->izq=nodo;
switch (nodo1->FE){
case 0: nodo->FE=1;
nodo1->FE=-1;
*BO=false;
break;
case 1: nodo->FE=0;
nodo1->FE=0;
*BO=false;
break;
}
nodo=nodo1;
}
else
{ //Rotacion DI
nodo2=nodo1->izq;
nodo->der=nodo2->izq;
nodo2->izq=nodo;
nodo1->izq=nodo2->der;
nodo2->der=nodo1;

if (nodo2->FE==1)
nodo->FE=-1;
else
nodo->FE=0;

if (nodo2->FE==-1)
nodo1->FE=1;
else
nodo1->FE=0;

nodo=nodo2;
nodo2->FE=0;
}
break;
}
}
   *nodocabeza=nodo;
}

void Restructura2(NODO **nodocabeza, bool *BO)
{
NODO *nodo, *nodo1, *nodo2;
   nodo=*nodocabeza;
   if ( *BO==true )
   {
switch(nodo->FE)
{
case 1: nodo->FE=0;
break;
case 0: nodo->FE=-1;
*BO=false;
break;
case -1: //reestructuracion del arbol
nodo1=nodo->izq;
if(nodo1->FE<=0)
{ //rotacion II
nodo->izq=nodo1->der;
nodo1->der=nodo;
switch (nodo1->FE)
{
case 0: nodo->FE=-1;
nodo1->FE=1;
*BO=false;
break;
case -1: nodo->FE=0;
nodo1->FE=0;
*BO=false;
break;
}
nodo=nodo1;
}
else
{ //Rotacion ID
nodo2=nodo1->der;
nodo->izq=nodo2->der;
nodo2->der=nodo;
nodo1->der=nodo2->izq;
nodo2->izq=nodo1;

if (nodo2->FE==-1)
nodo->FE=1;
else
nodo->FE=0;

if (nodo2->FE==1)
nodo1->FE=-1;
else
nodo1->FE=0;

nodo=nodo2;
nodo2->FE=0;
}
break;
}
}
   *nodocabeza=nodo;
}

void Borra(NODO **aux1, NODO **otro1, bool *BO)
{
NODO *nodo, *aux, *otro;
   aux=*aux1;
   otro=*otro1;
   if ( aux->der!=NULL )
{
Borra(&(aux->der),&otro,BO);
Restructura2(&aux,BO);
}
else
{
otro->info=aux->info;
aux=aux->izq;
*BO=true;
}
*aux1=aux;
*otro1=otro;
}

void EliminacionBalanceado(NODO **nodocabeza, bool *BO, int infor)
{
NODO *nodo, *otro;
   nodo=*nodocabeza;
   if(nodo!=NULL)
{
if( infor < nodo->info )
{
EliminacionBalanceado(&(nodo->izq),BO,infor);
Restructura1(&nodo,BO);
}
else
{
if( infor > nodo->info )
{
EliminacionBalanceado(&(nodo->der),BO,infor);
Restructura2(&nodo,BO);
}
else
{
otro=nodo;
if (otro->der==NULL)
{
nodo=otro->izq;
*BO=true;
}
else
{
if (otro->izq==NULL)
{
nodo=otro->der;
*BO=true;
}
else
{
Borra(&(otro->izq),&otro,BO);
Restructura1(&nodo,BO);
delete(otro);
}
}
}
}
}
else
{
cout<<"\nEl nodo NO se encuentra en el arbol\n"<<endl;
system("pause");
}
*nodocabeza=nodo;
}
[/color]
3  Programación / Programación C/C++ / Re: arbol binario en: 14 Diciembre 2010, 22:08 pm
Algunas operaciones que se les puede implementar aun arbol binario.




Código:
using namespace std;

struct NODO{
int dato;
struct NODO *izq;
struct NODO *der;
};

void crearArbol(NODO **cabeza);
void insertar(NODO **cabeza, int elemento);
void inorder(NODO *cabeza), preorder(NODO *cabeza);
void postorder(NODO *cabeza);
NODO *eliminar(NODO *cabeza, int elemento);

int main()
{
   char opcion;
   int elemento;
   NODO *borrado, *raiz;
   clrscr();
   crearArbol(&raiz);
   //raiz=NULL;
   
   for(;;){
      system("cls");
      printf("\tARBOLES BINARIOS DE BUSQUEDA\n\n");
      printf("(0) SALIR\n(1) Insertar\n(2) Eliminar\n(3) Inorder\n(4) Preorder\n(5) Postorder\n");
      printf("\n\tDigite su opcion ---> ");
     
      switch(opcion=getche()){
         case '0':
            exit(0);
         case '1':
            system("cls");
            printf("\nIngrese elemento a insertar: ");
            scanf("%d", &elemento);
            insertar(&raiz, elemento);
            break;
         
         case '2':
            if(raiz==NULL){
               printf("\nNo hay nodos en al arbol\n\n");
               break;
            }
            else{
               printf("\nIngrese dato a eliminar: ");
               scanf("%d", & elemento);
               borrado=eliminar( raiz, elemento);
               if(borrado==NULL)
                  printf("\nDato no encontrado\n\n");
               break;
            }         
         case '3':
            system("cls");
            printf("\nEl arbol es: ");
            inorder(raiz);
            system("pause");
            break;
         case '4':
            system("cls");
            printf("\nEl arbol es: ");
            preorder(raiz);
            break;
         case '5':
            system("cls");
            printf("\nEl arbol es: ");
            postorder(raiz);
            break;
      }
      printf("\n\n");
   }


   system("pause");
   return(0);
}
void crearArbol(NODO **cabeza)
{
   *cabeza=NULL;   
}
void insertar(NODO **cabeza, int elemento)
{

   if(*cabeza==NULL){
      *cabeza= (NODO *) malloc(sizeof(NODO));
     
      if(*cabeza==NULL){
         printf("No hay memoria\n");
         return;
      }     
      (*cabeza)->dato=elemento;
      (*cabeza)->izq=NULL;
      (*cabeza)->der=NULL;
   }
   else
      if(elemento< (*cabeza)->dato)
         insertar(& (*cabeza)->izq, elemento);
      else
         if(elemento> (*cabeza)->dato)
            insertar(& (*cabeza)->der, elemento);
         else
            printf("\nNo puede insertar: valor duplicado\n\n");

}

NODO *eliminar(NODO *cabeza, int elemento)
{
   NODO *p, *p2;
   
   if(elemento==cabeza->dato){
      if(cabeza->izq==cabeza->der){
         free(cabeza);
         return(NULL);
      }
     
      else
         if(cabeza->izq==NULL){
            p=cabeza->der;
            free(cabeza);
            return(p);
         }
     
         else
            if(cabeza->der==NULL){
               p=cabeza->izq;
               free(cabeza);
               return(p);
            }     
            else{
               p2=cabeza->der;
               p=cabeza->der;
               while(p->izq) p=p->izq;
                  p->izq=cabeza->izq;
               free(cabeza);
               return(p2);
            }
   }
   
   if(cabeza->dato<elemento)
      cabeza->der=eliminar(cabeza->der, elemento);
   else
      cabeza->izq=eliminar(cabeza->izq, elemento);
   return(cabeza);
}


void inorder(NODO *cabeza)
{
   if(cabeza!=NULL){
      inorder(cabeza->izq);
      printf("%d ",cabeza->dato);
      inorder(cabeza->der);
   }
}

void preorder(NODO *cabeza)
{
   if(cabeza!=NULL){
      printf("%d ", cabeza->dato);
      preorder(cabeza->izq);
      preorder(cabeza->der);
   }
}

void postorder(NODO *cabeza)
{
   if(cabeza!=NULL){
      postorder(cabeza->izq);
      postorder(cabeza->der);
      printf("%d ",cabeza->dato);
   }
}
void salvar(NODO **cabeza, int elemento)
{
   NODO *p, *p2;
   if(elemento==cabeza->dato){
      if(cabeza->izq==cabeza->der){
         free(cabeza);
         return(NULL);
      }
   if (elemento > 0){
      if ()
         moverDrcha(actual, k);
      else
         combina(actual, k);

   else /* Sólo tiene "hermano" derecho */
      if (actual->ramas[1]->cuenta > m/2)
         moverIzqda(actual, 1);
      else
         combina(actual, 1);
}
[/color]
4  Programación / Programación C/C++ / Numeros aleatorios en C en: 14 Diciembre 2010, 21:22 pm
Aqui les dejo un programa de generacion de numeros aleatorios y cuya salida me devuelve el mayor de los aleatorios , espero que lo sepan usar , haber si por alli alguien me puede facilitar programas resueltos en C++

ATTE : ANTON RAMIREZ , LEONARDO VLADIMIR  (ALUMNO UNI)

Código:
//MACROS
#define randomize (srand(time(0)))
//Retorna un numero aleatorio [0, num-1]
#define random(num) (rand()%(num))
#define TOPE 1000
#define MAX(x,y) ((x)>(y)?(x):(y))

using namespace std;

int main()
{
   int i, n, mx, y;
   randomize;
   mx=random(TOPE);
   printf("Ingrese la cantidad de numeros a mostrar :");
   scanf("%d", &n);
   for(i=0;i<n;){
      y=random(TOPE);
      mx=MAX(mx, y);
      printf("%3d ", y);
      i=i+1;
   }
   printf("\n\nMayor NUMERO : %d ", mx);
   printf("\n\n");
   system("pause");
   return(0);
}
[/color][/font]
5  Programación / Programación C/C++ / operaciones basicas con listas Simples y Dobles.... en: 14 Diciembre 2010, 21:10 pm
A continuación se presentan los algoritmos de operaciones con listas. La estructura es:
Para todas las acciones, Cab es un apuntador al primer nodo de la lista
Utilizaremos una notación para usarla en nuestros algoritmos de tal modo que estas sean independientes de cualquier lenguaje de programación.
Si P es un apuntador (puntero) del tipo NODO entonces P.Val hace referencia a la parte valor (información) del nodo apuntado por P de la misma manera P.Sgte hace referencia a la parte dirección siguiente del nodo apuntado por P..
En esta oportunidad implemento una lista dinamica, pero queda de antemano que existe la implementacion de lista estatica , osea usando vectores , haber si alguien lo obtine por alli , o mas aplicaciones de listes simples , hay tambien listas dobles y logicamente la lista circular , en esta oportunidad les dejo operaciones de listas simples.


ATTE : ANTON RAMIREZ , LEONARDO VLADIMIR  (ALUMNO UNI)

 Crea una lista enlazada de simple anadiendo nodos de numeros pares al final de la lista.

Código
  1. [li]// Aqui NODO debe ser global porque pude declararse en cualquier parte del programa
  2. struct NODO
  3. {
  4. int Val;
  5. NODO *Sgte;
  6. };
  7.  
  8. //Crea una lista vacia
  9. void CrearLista (NODO **Cab, NODO **Final);
  10.  
  11. // Crea una Lista de numeros Pares anadiendo al final de la lista
  12. void CrearLPares(NODO **Cab, NODO **Final);
  13.  
  14. // Muestra la Lista
  15. void MostrarLPares(NODO *Cab);
  16.  
  17. // Predicado que devuelve verdad si X es Par y falso en otro caso
  18. bool VrfcaPar(int x);
  19.  
  20. // Funcion principal
  21. int main()
  22. {
  23. NODO *L1; // Apuntador de tipo NODO para apuntar al primer elemento de la lista
  24. NODO *U1; // Apuntador de tipo NODO para apuntar al ultimo elemento de la lista
  25. //Creamos la lista L1 vacia
  26. CrearLista(&L1, &U1);
  27. // Llenamos la lista L1 con elementos pares
  28. CrearLPares(&L1, &U1);
  29. //Mostramos la lista L1 de pares
  30. MostrarLPares(L1);
  31.  
  32. system("PAUSE");
  33. return(0);
  34. }
  35.  
  36. void CrearLista (NODO **Cab, NODO **Final)
  37. {
  38. *Cab=NULL;
  39. *Final=NULL;
  40. }
  41.  
  42. void CrearLPares(NODO **Cab, NODO **Final)
  43. {
  44. int Num, Ctdor, i;
  45. NODO *P;
  46. Ctdor = 0; i = 1;
  47. //system("CLS");
  48. cout <<"Cuanto numeros pares desea ingresar " ;
  49. cin >>Num;
  50. while(Ctdor < Num)
  51. {
  52. if(VrfcaPar(i))
  53. {
  54. cout<<"Elemento ---> "<<i<<endl;
  55. //P = new NODO; // Que pasa si no hay memoria suficiente ?
  56. P = (NODO*)malloc(sizeof(NODO)); // Que pasa si no hay memoria suficiente ?
  57. if(*Cab == NULL)
  58. {
  59. P->Val = i;
  60. P->Sgte=NULL;
  61. *Cab = P;
  62. *Final =P;
  63. }
  64. else
  65. {
  66. P->Val = i;
  67. P->Sgte=NULL;
  68. (*Final)->Sgte = P;
  69. }
  70. *Final = P;
  71. //(*Final)->Sgte = NULL;
  72. Ctdor = Ctdor + 1;
  73. }
  74. i = i + 1;
  75. }
  76. system("PAUSE");
  77. }
  78.  
  79.  
  80. bool VrfcaPar(int x)
  81. {
  82. if(x%2 == 0)
  83. {
  84. return(true);
  85. }
  86. else
  87. {
  88. return(false);
  89. }
  90.  
  91. }
  92.  
  93. void MostrarLPares(NODO *Cab)
  94. {
  95. //system("CLS");
  96. // Utilizamos una variable auxiliar para desplazarnos en la lista
  97. NODO *P;
  98. printf("\nlista = < ");
  99. P = Cab;
  100. while(P != NULL)
  101. {
  102. cout<<P->Val<<" ";
  103. P = P->Sgte;
  104. }
  105. cout<<">"<<endl;
  106. system("PAUSE");
  107. }[/color][/li]
  108. [li][/li]
  109. [/list]

Código:
// Listas Dobles
using namespace std;

typedef int TD;// crea un sinomino de int

struct NODO
{
 TD val;
 NODO *ante;
 NODO *sgte;
};
void crearLista(NODO **Cabi, NODO **Cabu);// doble apúntador porque *cab es apuntador
void insertarIni(NODO **Cabi,NODO **Cabu, TD dato);
void mostrarNodos(NODO *Cabi);

int main()
{
 NODO *ai, *au;
 crearLista(&ai, &au);

 insertarIni(&ai,&au, 10);
 insertarIni(&ai,&au, 20);
 insertarIni(&ai,&au, 30);

 mostrarNodos(ai);
 
 
 cout <<("\n\n");
 system("pause");
 return(0);
}
 
void crearLista(NODO **Cabi, NODO **Cabu)// doble apúntador porque *cab es apuntador
{
 *Cabi=NULL;
 *Cabu=NULL;
 
}
 
void insertarIni(NODO **Cabi,NODO **Cabu, TD dato)
{
 NODO * p;
 
 p=(NODO*)malloc(sizeof(NODO));//MALLOC DEVUELVE LA VARIABLE NO A VOID SINO A NODO
 
 if(p==NULL){// hubo exito en la separacion de memoria
 printf("nO HAY espacio en la RAM");
 exit(0);
 }
 else{
 p->val=dato;
 p->ante=NULL;
 p->sgte=NULL;
 if(*Cabi==NULL){
 *Cabi=p;
 *Cabu=p;
 }
 else{
 p->sgte=*Cabi;
 (*Cabi)->ante=p;//ya que el * y -> tienen la misma prioridad.
 *Cabi=p;
 }
 }
}
void mostrarNodos(NODO *Cabi)
{
 NODO *p;
 p=Cabi;
 while(p!=NULL){//si pusiera p->sgte!=NULL no mostraria al 10 yaq psgte no existe
 cout << p->val<<",";
 p=p->sgte;
 }
} [/code=c]
6  Programación / Programación C/C++ / Vectores Dinamicos en: 14 Diciembre 2010, 20:50 pm
Los vectores dinamicos tiene las mismas propiedades que los vectores estaticos lo que varia  es la creación en la cual las dimensiones del mismo son ingresadas en tiempo de ejecucion. Una vez asignadas estas dimensiones ya no se pueden modificar.
En este programa se puede relizar las operaciones de leer,mostrar,ordenar y eliminar un vector dinamico, ademas de las operaciones insertar y eliminar elementos del vector dinamico.
 Bueno al realizar este programa tengo una dificultad para el insertar y eliminar dinamicamente , me parecio interesante realizar esto , porque lo logico seria utilizar pilas y colas , pero en fin espero que me puedan apoyar que le falta a mi algoritmo para que no se cuelgue .


ATTE : ANTON RAMIREZ , LEONARDO VLADIMIR  (ALUMNO UNI)


Código:
[list]
[li][ftp][/ftp][tt][color=blue]using namespace std;

int Menu();
void Linea();
void LeerVector(int **X, int *dimX);
void MostrarVector(int *X, int dimX);
void InsertarxPosic(int **X, int *dimX, int Pos);
void InsertarxValor(int **X, int *dimX, int Val);
void EliminarxPosic(int **X, int *dimX, int Pos);
void EliminarxValor(int **X, int *dimX, int Val);
void Redimensionar_Aumentar(int *X, int *dimX);
void Redimensionar_Disminuir(int *X, int *dimX);
void Redimensionar1(int *X, int *dimX);
void Redimensionar2(int *X, int *dimX);

int main()
{
   int *A, na, posic, valor, Opcion;
   A = NULL;
   do{
      Opcion = Menu();
      switch(Opcion)
      {
         case 1 : system("cls"); Linea();
               cout<<"\t\tRUTINA DE CREACION\n"; Linea();
               printf("\n");
               LeerVector(&A, &na);
               break;
         case 2 : system("cls"); Linea();
               cout<<"\t      RUTINA DE VIZUALIZACION\n"; Linea();
               printf("\n");
               MostrarVector(A, na);
               printf("\n\n"); system("pause");  
               break;
         case 3 : system("cls"); Linea();
               cout<<"\t    RUTINA INSERTA POR POSICION\n"; Linea();
               printf("\n");
               MostrarVector(A, na);
               if(A!=NULL){
                  cout<<"\n\nIngrese  la  POSICION => ";
                  cin>>posic;
                  posic = posic-1;
                  InsertarxPosic(&A, &na, posic);
               }
               printf("\n\n"); system("pause");
               break;
         case 4 : system("cls"); Linea();
               cout<<"\t    RUTINA ELIMINA POR POSICION\n"; Linea();
               printf("\n");
               MostrarVector(A, na);
               if(A!=NULL){
                  cout<<"\n\nIngrese la POSICION => ";
                  cin>>posic;
                  posic = posic-1;
                  EliminarxPosic(&A, &na, posic);
               }
               printf("\n\n"); system("pause");
               break;
         case 5 : system("cls"); Linea();
               cout<<"\t    RUTINA INSERTA POR VALOR\n"; Linea();
               printf("\n");
               MostrarVector(A, na);
               if(A!=NULL){
                  cout<<"\n\nIngrese el VALOR => ";
                  cin>>valor;
                  InsertarxValor(&A, &na, valor);
               }
               printf("\n\n"); system("pause");
               break;
         case 6 : system("cls"); Linea();
               cout<<"\t    RUTINA ELIMINA POR VALOR\n"; Linea();
               printf("\n");
               MostrarVector(A, na);
               if(A!=NULL){
                  cout<<"\n\nIngrese el VALOR => ";
                  cin>>valor;
                  EliminarxValor(&A, &na, valor);              
               }
               printf("\n\n"); system("pause");
               break;
         case 0 :
               free(A);
               A=NULL;
               exit(1);
      }
   }while(Opcion);
  
  printf("\n");
  system("PAUSE");
  return(0);
}

int Menu()
{
   int op;
   do{
   system("cls");
   printf("\n\t    OPERACIONES CON VECTORES DINAMICOS \n\n");
   printf("\t1.  Crear  \n");
   printf("\t2.  Mostrar \n");
   printf("\t3.  Insertar por Posicion \n");
   printf("\t4.  Eliminar por Posicion \n");
   printf("\t5.  Insertar por Valor \n");
   printf("\t6.  Eliminar por Valor \n");
   printf("\t0.  SALIR \n\n");
   printf("\tDigite su opcion => ");
   scanf("%d",&op);
  }while(op<0 || op>7);
  return(op);
}

void LeerVector(int **X, int *dimX)
{
   int N, i, val;
   printf("Ingrese dimension del vector : ");
   scanf("%d", &N);  
  
   *X=(int*)malloc(N*sizeof(int));
  
   if(*X == NULL)
   {
      printf("Error: No hay memoria suficiente...\n");
      system("pause");
      exit(1);
   }
   else
   {
      printf("\nIngrese los datos del vector ...\n\n");
      for(i=0;i<N;i++)
      {
         printf("X[%d] = ", i + 1);
         scanf("%d", *X+i);
      }
      *dimX=N;
   }
      
}

void MostrarVector(int *X, int dimX)
{
   if(X==NULL){
      printf("El vector esta VACIO ...");
   }
   else{
      printf("\nVECTOR [%d] = ", dimX);
      for(int i=0;i<dimX;i++)
      {
         printf("%4d", *(X+i));
      }
   }
}
  
void InsertarxPosic(int **X, int *dimX, int Pos)
{
   int val;
  
   if(*X == NULL){
      printf("\nEl vector esta VACIO ...\n\n");
   }
   else{
      if(Pos<*dimX && Pos>=0){
         Redimensionar_Aumentar(*X, dimX); //Redimensionar1(*X, dimX);
         for(int i=*dimX; i>Pos; i--){
            *(*X+i) = *(*X+(i-1));
         }
         printf("\n...Valor a Insertar -> "); scanf("%d", &val);
         *(*X+Pos) = val;
         MostrarVector(*X, *dimX);
      }
      else{
         printf("\nError: Posicion fuera de rango ...\n");
      }
   }
}
  

void InsertarxValor(int **X, int *dimX, int Val)
{
   int i, Hallado, Pos;
  
   i=0; Hallado=0;
   if(*X == NULL){
      printf("\nEl vector esta VACIO ...\n\n");
   }
   else{
         while(i<*dimX && !Hallado){
            if(*(*X+i)==Val){
            Hallado = 1;
            Pos = i;
            }
            i = i+1;
         }
   }
   if(Hallado){
      InsertarxPosic(&*X, dimX, Pos);
   }
   else{
      printf("\nError: Valor no encontrado ...\n");
   }
}

void EliminarxPosic(int **X, int *dimX, int Pos)
{  
  
   if(*X == NULL){
      printf("\nEl vector esta VACIO ...\n\n");
   }
   else{
      if(Pos<*dimX && Pos>=0){
         for(int i=Pos; i<*dimX; i++){
            *(*X+i) = *(*X+(i+1));
         }
         Redimensionar_Disminuir(*X, dimX); //Redimensionar2(*X, dimX);    
         MostrarVector(*X, *dimX);
      }
      else{
         printf("\nError: Posicion fuera de rango ...\n");
      }
   }
}

void EliminarxValor(int **X, int *dimX, int Val)
{
   int i, Hallado, Pos;
  
   i=0; Hallado=0;
   if(*X == NULL){
      printf("\nEl vector esta VACIO ...\n\n");
   }
   else{
      while(i<*dimX && !Hallado){
         if(*(*X+i)==Val){
            Hallado = 1;
            Pos = i;
         }
      i = i+1;
      }
   }  
   if(Hallado){
      EliminarxPosic(&*X, dimX, Pos);
   }
   else{
      printf("\nError: Valor no encontrado ...\n");
   }
}
  
void Redimensionar1(int *X, int *dimX)
{
   X = (int *)realloc(X,(*dimX+1)*sizeof(int));
   *dimX=*dimX+1;  
}

void Redimensionar2(int *X, int *dimX)
{
   X = (int *)realloc(X,(*dimX-1)*sizeof(int));  
   *dimX=*dimX-1;
}

void Redimensionar_Aumentar(int *X, int *dimX)
{
   int *A;
   int n=*dimX;
   n = n+1;
   A = (int *)malloc(n*sizeof(int));
   for(int i=0; i<n-1;){
      *(A+i) = *(X+i);
      i = i+1;
   }
   *dimX = n;
   X = A;
}

void Redimensionar_Disminuir(int *X, int *dimX)
{
   int *A;
   int n=*dimX;
   n = n-1;
   A = (int *)malloc(n*sizeof(int));
   for(int i=0; i<n;){
      *(A+i) = *(X+i);
      i = i+1;
   }
   *dimX = n;
   X = A;
}

void Linea()
{
   printf("\t==================================\n");
}[/color][/tt][/li]
[li][/li]
[/list]
7  Programación / Programación C/C++ / Re: MENU CON PROCEDIMIENTOS en: 14 Diciembre 2010, 15:38 pm
Bueno lamento haber ofendido a alguien no quise hacer tareas , en realidad no sabia las reglas del juego ok , tienen razon nada de tareas , vamos hacer futuros ingenieros , para mi lo ideal seria intercambiar informacion no pedir que te hagan la tarea , los algoritmos son para analizar su solucion y una mejora eficaz , bueno ya entendi el mensaje , gracias
8  Programación / Programación C/C++ / Re: MENU CON PROCEDIMIENTOS en: 13 Diciembre 2010, 04:32 am
No te preocupes amigo aqui tengo la solucion a tu problema claro que el decorado no me dio tiempo , pero eso es facil aqui te dejo el pseudocodigo pongo el using namespace std; porque utilizo el devc-++ bueno espero que te sirva esta con el menu :
ojo el ingreso esta implementado con numeros aleatorios , siempre hay que innovar en programacion , lo ves en opcion de mostrar , hay un insertar por posicion , espero que lo emplees bien , saludos:


Código
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <conio.h>
  5. #include <time.h>
  6. #define Max 12000
  7. #define TOPE 1000
  8. #define randomize (srand(time(0)))
  9. #define random(num) (rand()%(num))
  10. using namespace std;
  11.  
  12. int Menu();
  13. void leerVector(int X[Max],int *dimX);
  14. void mostrarVector(int X[Max],int dimX);
  15. void insertarxPosic(int X[Max],int *dimX,int posi,int dato);
  16. void eliminarxPosic(int X[Max],int *dimX,int posi);
  17. void ordenarxBurbuja(int X[Max],int *dimX);
  18. int main()
  19. {
  20. int opcion,A[Max],na;
  21. do{
  22. opcion=Menu();
  23. switch(opcion){
  24. case 1: {
  25. system("cls");
  26. printf("\n*Rutina de lectura*\n\n");
  27. leerVector(A,&na);
  28. system("pause");
  29. system("cls");
  30. break;
  31. }
  32. case 2: {
  33. system("cls");
  34. printf("\n*Mostrando el Vector Generado*\n\n");
  35. mostrarVector(A,na);
  36. printf("\n\n");
  37. system("pause");
  38. system("cls");
  39. break;
  40. }
  41. case 3: {
  42. system("cls");
  43. int d,pos,p;
  44. printf("\n*Insercion de un elemento por posicion*");
  45. cout<<"\n\nIngresar el dato a insertar [0,999] : ";
  46. cin>>d;
  47. cout<<"Ingresar la posicion a insertar : ";
  48. cin>>p;
  49. pos=p-1;
  50. insertarxPosic(A,&na,pos,d);
  51. printf("\n\n");
  52. system("pause");
  53. system("cls");
  54. break;
  55. }
  56. case 4: {
  57. system("cls");
  58. int ps,pp;
  59. printf("\n*Eliminacion de un elemento por posicion*");
  60. cout<<"\n\nIngresar la posicion del dato que desea eliminar: ";
  61. cin>>ps;
  62. eliminarxPosic(A,&na,ps);
  63. printf("\n\n");
  64. system("pause");
  65. system("cls");
  66. break;
  67. case 5: {
  68. system("cls");
  69. printf("\n*Ordenamiento por burbuja*\n\n");
  70. ordenarxBurbuja(A,&na);
  71. printf("\n\n");
  72. system("pause");
  73. system("cls");
  74. break;
  75. }
  76. }
  77. }
  78. }while(opcion != 0);
  79.  
  80.  
  81. return(0);
  82. }
  83.  
  84. int Menu()
  85. {
  86. int op;
  87.  
  88. printf(" M E N U \n\n");
  89. printf(" 0. Terminar \n");
  90. printf(" 1. LeerVector \n");
  91. printf(" 2. MostrarVector \n");
  92. printf(" 3. InsertarxPosic \n");
  93. printf(" 4. EliminarxPosic \n");
  94. printf(" 5. ORDENARX BURBUJA \n");
  95. do{
  96. printf("Digite su opcion ---> ");
  97. scanf("%d",&op);
  98. }while(op<0 || op>5);
  99. return(op);
  100. }
  101.  
  102. void leerVector(int X[Max],int *dimX)
  103. {
  104. int n,i,val;
  105. randomize;
  106. printf("Ingrese la dimension de su vector: ");
  107. cin>>n;
  108. if(n<Max){
  109. for(i=0;i<n;){
  110. val=random(TOPE);
  111. X[i]=val;
  112. i=i+1;
  113. }
  114. *dimX=n;
  115. printf("\n...Rutina de Lectura de Numeros Aleatorios Completada...\n\n");
  116. }else{
  117. printf("Dimension fuera de Rango...\n\n");
  118. }
  119. }
  120.  
  121. void mostrarVector(int X[Max],int dimX)
  122. {
  123. int i,val;
  124. for(i=0;i<dimX;){
  125. val=X[i];
  126. if(i!=0){
  127. if(i%20==0){
  128. printf("\n");
  129. }
  130. }
  131. printf("%3d ",val);
  132. i=i+1;
  133. }
  134. }
  135.  
  136. void insertarxPosic(int X[Max],int *dimX,int posi,int dato)
  137. {
  138. int i,N;
  139. N=*dimX;
  140. N=N+1;
  141. i=N;
  142. if(i<Max&&posi<N){
  143. while(i>posi){
  144. X[i]=X[i-1];
  145. i=i-1;
  146. }
  147. X[posi]=dato;
  148. *dimX=N;
  149. printf("\n%d INSERTADO en posicion %d\n\n",dato,posi+1);
  150. mostrarVector(X,*dimX);
  151. }else{
  152. printf("Dimension o Posicion fuera de Rango\n");
  153. }
  154. }
  155.  
  156. void eliminarxPosic(int X[Max],int *dimX,int posi)
  157. {
  158. int i,N;
  159. N=*dimX;
  160. if(posi<N){
  161. printf("\n%d ha sido ELIMINADO de posicion %d\n\n",X[posi-1],posi);
  162. i=posi-1;
  163. while(i<*dimX){
  164. X[i]=X[i+1];
  165. i=i+1;
  166. }
  167. *dimX=*dimX-1;
  168. mostrarVector(X,*dimX);
  169. }else{
  170. if(posi==N){
  171. printf("\n%d ha sido ELIMINADO de posicion %d\n\n",X[posi-1],posi);
  172. *dimX=*dimX-1;
  173. mostrarVector(X,*dimX);
  174. }else{
  175. printf("...Posicion fuera de Rango...");
  176. }
  177. }
  178. }
  179. void ordenarxBurbuja(int X[Max],int *dimX)
  180. {
  181. int i,j,aux,Np=*dimX-1;
  182. long ini,fin;
  183. ini = clock();
  184. for(i=1;i<=Np;i++){
  185. for(j=Np;j>=1;j--){
  186. if(X[j-1]>X[j]){
  187. aux=X[j-1];
  188. X[j-1]=X[j];
  189. X[j]=aux;
  190. }
  191. }
  192. }
  193. mostrarVector(X,*dimX);
  194. fin=clock();
  195. printf("\n\ntiempo de proceso %ld ",fin-ini);
  196. printf("\ntiempo en segundos %f\n\n",(fin-ini)/(float)CLOCKS_PER_SEC);
  197. }
AGRADECER NO CUESTA NADA


Lh: Utiliza las etiquetas GeShi para poner código.
9  Programación / Programación C/C++ / OPERACIONES BASICAS CON FILES en: 13 Diciembre 2010, 04:17 am
hola a todos gracias por tu consejo Sagrini en realidad quisiera pedirte si me puedes brindar material de como empezar en linux , estoy muy implementado en dev y quiero tocar otras opciones , bueno en esta oportunidad te dejo un code sobre operaciones con files , compilalo con el dev-c++ y presiona F9 si gusta para compilar rapido .

AQUI podras apreciar aparte de las operaciones basicas como insertar registros , eliminar registros , mostrar registros , un actualizar con punteros , metodos de ordenamiento por codigo y por nombre es novedoso estos metodos , tambien hay varias decoraciones implemente algoritmos para capturar cuadros y hora -fecha del sistema este proyecto me costo muxo , quiero compartirlo con ustedes , haber Sagrini si das tu visto bueno a mi proyecto y como dices apoyame para comenzar con Linux , eh echo de todo un poco de todos los temas en dev++ pero ya quiero variar , ok espero tu respuesta y seguir en contacto si gustas seria bueno obtener tu ms para intercambiar informacion bueno me despido espero que puedan apreciar mi proyecto :



ATTE : ANTON RAMIREZ , LEONARDO VLADIMIR  (ALUMNO UNI)


Código
  1. #include <windows.h>//para los message box
  2. #include <iostream>
  3. #include <stdio.h> // Operaciones de archivos
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <conio.h>
  7. #include <ctype.h> // Operaciones toupper/tolower
  8. using namespace std;
  9.  
  10. struct CLIENTE
  11. {
  12. char Cod[5];
  13. char Nombre[25];
  14. char Direccion[28];
  15. char Tipo;
  16. char tel[10];
  17.  
  18. };
  19. // Declaracion global de la variable "Registro" de tipo struct CLIENTE
  20. struct CLIENTE Registro;
  21.  
  22. // Declaracion global de la variable "*F" (apuntador de tipo archivo)
  23. FILE *F;
  24.  
  25. int MenuCLIENTE();
  26. void IngresarRegCLIENTE(); // Denominado tambien rutina de Altas
  27. void BuscarxCodCLIENTE(); // Denominado tambien rutina de Consultas
  28. void ActualizacionxCodCLIENTE(); // Denominado tambien rutina de Modificaciones
  29. void EliminacionLogicaxCodCLIENTE(); // Denominado tambien rutina de Baja Logica
  30. void EliminacionFisicaxCodCLIENTE(); // Denominado tambien rutina de Baja Fisica
  31. void MostrarRegCLIENTE();
  32. void Encabezado1();
  33. void Raya58();
  34. void Raya60();
  35. int Menu();
  36. void ordenarxcod();
  37. void ordenarxnom();
  38. void cuadro(int i,int j,int k,int l);
  39. int main()
  40. {
  41. int Opcion;
  42. do
  43. {
  44. Opcion = MenuCLIENTE();
  45. switch(Opcion)
  46. {
  47. case 1 : IngresarRegCLIENTE();
  48. break;
  49. case 2 : BuscarxCodCLIENTE();
  50. break;
  51. case 3 : ActualizacionxCodCLIENTE();
  52. break;
  53. case 4 : EliminacionLogicaxCodCLIENTE();
  54. break;
  55. case 5 : EliminacionFisicaxCodCLIENTE();
  56. break;
  57. case 6 : MostrarRegCLIENTE();
  58. break;
  59. case 7 : ordenarxcod();
  60. break;
  61. case 8 : ordenarxnom();
  62. break;
  63. }
  64. }while(Opcion != 0);
  65. system("pause");
  66. MessageBox(NULL, "Adios Gracias Por Usar Este Programa", "Adios =(", MB_ICONINFORMATION | MB_OK | MB_SYSTEMMODAL);
  67. return(0);
  68. }
  69.  
  70. int MenuCLIENTE()
  71. {
  72. int i;
  73. textbackground(BLUE);
  74. do
  75. {
  76. system("cls");
  77. cuadro(1,1,80,25);
  78. cuadro(28,2,50,4);
  79. textcolor(LIGHTGREEN);
  80. /*cout << "\n\n\r A R C H I V O D E C L I E N T E S";
  81.  cout << "\n\n\r Archivos SECUENCIALES en Lenguaje C ";
  82.  textcolor(WHITE);
  83.  cout << "\n\n\n\r 1.- INGRESAR Registros";
  84.  cout << "\n\r 2.- BUSCAR por CODIGO";
  85.  cout << "\n\r 3.- ACTUALIZAR Datos por CODIGO";
  86.  cout << "\n\r 4.- Eliminacion LOGICA por CODIGO";
  87.  cout << "\n\r 5.- Eliminacion FISICA por CODIGO (defragmentar)";
  88.  cout << "\n\r 6.- MOSTRAR Registros";
  89.  cout << "\n\r 7.- ORDENAR Registro por CODIGO";
  90.  cout << "\n\r 8.- ORDENAR Registro por NOMBRE";
  91.  textcolor(LIGHTRED);
  92.  cout << "\n\r 0.- TERMINAR";*/
  93. textcolor(WHITE);
  94. gotoxy(30,3);
  95. textcolor(LIGHTRED);
  96. printf("ARCHIVO DE CLIENTES");
  97. gotoxy(15,5);printf("0.- TERMINAR");
  98. textcolor(LIGHTGREEN);
  99. gotoxy(15,7);printf("1.- INGRESAR Registros");
  100. gotoxy(15,9);printf("2.- BUSCAR Regsitros por CODIGO");
  101. gotoxy(15,11);printf("3.- ACTUALIZAR Datos por CODIGO");
  102. gotoxy(15,13);printf("4.- ELIMINACION LOGICA por CODIGO");
  103. gotoxy(15,15);printf("5.- ELIMINACION FISICA (Defragmentar)");
  104. gotoxy(15,17);printf("6.- MOSTRAR Registros");
  105. gotoxy(15,19);printf("7.- ORDENAR Registros por CODIGO");
  106. gotoxy(15,21);printf("8.- ORDENAR Registros por NOMBRE");
  107. textcolor(LIGHTRED);
  108. gotoxy(15,23);printf(" Escojer su Opcion---------------------> ");
  109. textcolor(WHITE);
  110. cin >> i;
  111. }while(i<0 || i>8);
  112. return(i);
  113.  
  114. }
  115.  
  116. void IngresarRegCLIENTE()
  117. {
  118. char Codigo[15];
  119. system("cls");
  120.  
  121. cout << "\n\r INGRESAR REGISTROS DE CLIENTES";
  122. // Intenta abrir el archivo CLIENTES.SEC en modo de lectura/escritura
  123. F = fopen("Cliente.Sec","rb+");
  124. if(F == NULL)
  125. {
  126. // Crea el archivo en caso de no existir
  127. F = fopen("Cliente.Sec","wb");
  128. }
  129.  
  130. cout << "\n\n\n\rCodigo ---------> ";getchar();
  131. //gets(Codigo);
  132. cin>>Codigo;
  133. fread(&Registro,sizeof(Registro),1,F); // Lee el Registro, de tamano=sizeof(Registro) del archivo "F"
  134. // Ciclo mientras no se encuentre el final del archivo
  135. while(!feof(F))
  136. {
  137. if(strcmp(Registro.Cod, Codigo)== 0)
  138. {
  139. cout << "\n\n\n\rRegistro DUPLICADO ...!!!";
  140. fclose(F);
  141. getch();
  142. return;
  143. }
  144. fread(&Registro,sizeof(Registro),1,F);
  145. }
  146.  
  147. strcpy(Registro.Cod, Codigo);
  148. cout << "\n\rNombre ----------> ";getchar();
  149. gets(Registro.Nombre);
  150. cout << "\n\rDireccion ---------> ";
  151. gets(Registro.Direccion);
  152. cout << "\n\rTelefono/celular ---> ";
  153. gets(Registro.tel);
  154. cout << "\n\rTipo--> ";
  155. cin >> Registro.Tipo;
  156.  
  157. // Grabar el Registro completo
  158. fwrite(&Registro, sizeof(Registro), 1, F);
  159. fclose(F); // Cierra el archivo
  160.  
  161. cout << "\n\n\n\rCLIENTE registrado !!!\n";
  162. cout << "\n\r<<< ... PRESIONE ENTER para continuar >>>";
  163. getch();
  164. return;
  165. }
  166.  
  167. void BuscarxCodCLIENTE()
  168. {
  169. //Numero de producto que desea consultar
  170. char Codigo[15];
  171. system("cls");
  172.  
  173. cout << "\n\rBUSCAR REGISTROS POR CODIGO DE CLIENTES";
  174. // Intenta abrir el archivo CLIENTES.SEC, en modo de solo lectura
  175. F = fopen("Cliente.Sec","rb");
  176.  
  177. if(F == NULL)
  178. {
  179. cout << "\n\n\n\rNo existe el archivo !!!\n";
  180. cout << "\n\r<<< ... PRESIONE ENTER para continuar >>>";
  181. getch();
  182. return;
  183. }
  184.  
  185. cout << "\n\n\n\r Codigo ---------> "; getchar(); gets(Codigo);
  186.  
  187. // Lee el "Registro", de tamano=sizeof(Registro) del archivo "F"
  188. fread(&Registro, sizeof(Registro), 1, F);
  189.  
  190. while(!feof(F))
  191. {
  192. if(strcmp(Registro.Cod, Codigo)==0)
  193. {
  194. Encabezado1();
  195. printf("\n%-8s%-25s%-25s%12s %-5c",Registro.Cod,Registro.Nombre,Registro.Direccion, Registro.tel,Registro.Tipo);
  196. Raya60();
  197. getch();
  198. return;
  199. }
  200. fread(&Registro, sizeof(Registro), 1, F);
  201. }
  202. cout << "\n\rNo se encuentra ese registro !!!\n";
  203. fclose(F);
  204. cout << "\n\r<<< ... PRESIONE ENTER para continuar >>>";
  205. getch();
  206. return;
  207. }
  208.  
  209. void ActualizacionxCodCLIENTE()
  210. {
  211. // Codigo de CLIENTE que desea modificar
  212. char Codigo[15];
  213. int op;
  214. system("cls");
  215.  
  216. cout << "\n\rACTUALIZAR REGISTROS POR CODIGO DE CLIENTES";
  217. // Intenta abrir el archivo CLIENTES.dat en modo de lectura/escritura
  218. F = fopen("Cliente.Sec","rb+");
  219. if(F == NULL) // Valida la existencia del archivo
  220. {
  221. cout << "\n\n\n\rNo existe el archivo !!!\n";
  222. cout << "\n\r<<< ... PRESIONE ENTER para continuar >>>";
  223. getch();
  224. return;
  225. }
  226.  
  227. cout << "\n\n\n\rCodigo ---------> "; getchar(); gets(Codigo);
  228. // Lee el "Registro", de tamano=sizeof(Registro) del archivo "F"
  229. fread(&Registro, sizeof(Registro), 1, F);
  230.  
  231. while(!feof(F))
  232. {
  233. if(strcmp(Registro.Cod, Codigo)==0)
  234. {
  235. Encabezado1();
  236. printf("\n%-8s%-25s%-25s%12s %-5c",Registro.Cod,Registro.Nombre,Registro.Direccion, Registro.tel,Registro.Tipo);
  237. Raya60();
  238. cout << "\n\n\n\r";
  239. system("pause");
  240. do
  241. {
  242. op = Menu();
  243. switch(op)
  244. {
  245. case 1 : system("cls");
  246. textcolor(LIGHTGREEN);
  247. cout << "\n\n\r Actualizacion de Clientes";
  248. textcolor(WHITE);
  249. cout << "\n\n\n\rIngrese nuevo dato";
  250. cout << "\n\rNombre ---------> "; getchar(); gets(Registro.Nombre);
  251. system("cls");
  252. break;
  253. case 2 : system("cls");
  254. textcolor(LIGHTGREEN);
  255. cout << "\n\n\r Actualizacion de Clientes";
  256. textcolor(WHITE);
  257. cout << "\n\n\n\rIngrese nuevo dato";
  258. cout << "\n\rDireccion --------> ";getchar(); gets(Registro.Direccion);
  259. system("cls");
  260. break;
  261. case 3 : system("cls");
  262. textcolor(LIGHTGREEN);
  263. cout << "\n\n\r Actualizacion de Clientes";
  264. textcolor(WHITE);
  265. cout << "\n\n\n\rIngrese nuevo dato";
  266. cout << "\n\rTipo--> "; cin >> Registro.Tipo;
  267. system("cls");
  268. break;
  269.  
  270. }
  271. }while(op != 0);
  272.  
  273. /**Es necesario reposicionar el apuntador del archivo al principio del
  274.  * registro que desea modificar, ya que al leer un registro, el
  275.  * apuntador se posiciona en el registro siguiente
  276.  * La funcion ftell(F) devuelve la posicion donde se encuentra el
  277.  * apuntador
  278.  */
  279. fseek(F, ftell(F)-sizeof(Registro), SEEK_SET);
  280. // Graba el registro con los nuevos campos
  281. fwrite(&Registro, sizeof(Registro), 1, F);
  282. fclose(F);
  283. cout << "\n\n\n\rRegistro modificado !!!\n";
  284. cout << "\n\r<<< ... PRESIONE ENTER para continuar >>>";
  285. getch();
  286. return;
  287. }
  288. fread(&Registro, sizeof(Registro), 1, F);
  289. }
  290. cout << "\n\rNo se encuentra ese registro !!!\n";
  291. fclose(F);
  292. cout << "\n\r<<< ... PRESIONE ENTER para continuar >>>";
  293. getch();
  294. return;
  295. }
  296.  
  297. void EliminacionLogicaxCodCLIENTE()
  298. {
  299. //numero de codigo que desea eliminar
  300. char Codigo[15], op;
  301. system("cls");
  302.  
  303. cout << "\n\rELIMINACION LOGICA DE REGISTROS DE CLIENTES";
  304. F = fopen("Cliente.Sec","rb+");
  305. if(F == NULL) // Checa la existencia del archivo
  306. {
  307. cout << "\n\n\n\rNo existe el archivo !!!\n";
  308. cout << "\n\r<<< ... PRESIONE ENTER para continuar >>>";
  309. getch();
  310. return;
  311. }
  312.  
  313. cout << "\n\n\n\rCodigo --------> "; getchar(); gets(Codigo);
  314.  
  315. fread(&Registro, sizeof(Registro), 1, F);
  316. while(!feof(F))
  317. {
  318. if(strcmp(Registro.Cod, Codigo)==0)
  319. {
  320. Encabezado1();
  321. printf("\n%-8s%-25s%-25s%12s %-5c",Registro.Cod,Registro.Nombre,Registro.Direccion, Registro.tel,Registro.Tipo);
  322. Raya60();
  323.  
  324. strcpy(Registro.Cod, "----");
  325. strcpy(Registro.Nombre, "----");
  326. strcpy(Registro.Direccion, "----");
  327. Registro.Tipo = '0';
  328. do {
  329. cout << "\n\n\r¿... SEGURO que desea BORRARLO ...? [S/N] ---> ";
  330. cin>>op;
  331. op=toupper(op);
  332. }while(op!='S' && op!='N');
  333.  
  334. if(op == 'S')
  335. {
  336. /** Es necesario reposicionar el apuntador del archivo al principio del
  337.  * registro que desea modificar, ya que al leer un registro, el
  338.  * apuntador se posiciona en el registro siguiente
  339.  * La funcion ftell(F) devuelve la posicion donde se encuentra el
  340.  * apuntador
  341.  */
  342. fseek(F, ftell(F)-sizeof(Registro), SEEK_SET);
  343. fwrite(&Registro, sizeof(Registro), 1, F);
  344. cout << "\n\n\n\rRegistro eliminado !!!\n";
  345. }
  346. fclose(F);
  347. cout << "\n\r<<< ... PRESIONE ENTER para continuar >>>";
  348. getch();
  349. return;
  350. }
  351. fread(&Registro, sizeof(Registro), 1, F);
  352. }
  353. cout << "\n\rNo se encuentra ese registro !!!\n";
  354. fclose(F); // Cierra el archivo
  355. cout << "\n\r<<< ... PRESIONE ENTER para continuar >>>";
  356. getch();
  357. return;
  358. }
  359.  
  360. void EliminacionFisicaxCodCLIENTE()
  361. {
  362. //Variable para controlar el archivo temporal
  363. FILE *Temporal;
  364. system("cls");
  365.  
  366. cout << "\n\rELIMINACION FISICA DE REGISTROS DE CLIENTES";
  367. // Intenta abrir el archivo CLIENTES.SEC en modo de solo lectura
  368. F = fopen("Cliente.Sec","rb");
  369. // Valida la existencia del archivo
  370. if(F == NULL)
  371. {
  372. cout << "\n\n\n\rNo existe el archivo !!!\n";
  373. cout << "\n\r<<< ... PRESIONE ENTER para continuar >>>";
  374. getch();
  375. return;
  376. }
  377. // Crea el archivo Temporal.Sec
  378. Temporal = fopen("Temporal.Sec","wb");
  379.  
  380. fread(&Registro, sizeof(Registro), 1, F);
  381. while(!feof(F))
  382. {
  383. if(strcmp(Registro.Cod, "----")!= 0)
  384. // Graba el registro valido en el archivo temporal
  385. fwrite(&Registro, sizeof(Registro), 1, Temporal);
  386. //Lee el siguinete elemento del archivo
  387. fread(&Registro, sizeof(Registro), 1, F);
  388. }
  389. //fcloseall(); // Cierra todos los archivos abiertos
  390. fclose(F);
  391. fclose(Temporal);
  392. remove("Clientes.Sec"); //Elimina el archivo original
  393. rename("Temporal.Sec", "Clientes.Sec");
  394. //Renombra el archivo temporal con el nombre del archivo original
  395.  
  396. cout << "\n\n\n\rArchivo DEFRAGMENTADO ... !!!\n";
  397. cout << "\n\r<<< ... PRESIONE ENTER para continuar >>>";
  398. getch();
  399. return;
  400. }
  401.  
  402. void MostrarRegCLIENTE()
  403. {
  404. system("cls");
  405.  
  406. cout << "\n\r\t\t\tLISTADO DE REGISTROS DE CLIENTES\n\n";
  407. F = fopen("Cliente.Sec","rb");
  408. if(F == NULL)
  409. {
  410. cout << "\n\n\n\rNo existe el archivo !!!\n";
  411. cout << "\n\r<<< ... PRESIONE ENTER para continuar >>>";
  412. getch();
  413. return;
  414. }
  415.  
  416. Encabezado1();
  417. fread(&Registro, sizeof(Registro), 1, F);
  418. while(!feof(F))
  419. {
  420. printf("\n%-8s%-25s%-25s%12s %-5c",Registro.Cod,Registro.Nombre,Registro.Direccion, Registro.tel,Registro.Tipo);
  421. fread(&Registro,sizeof(Registro),1,F);
  422. }
  423. fclose(F); // Cierra el archivo
  424. Raya60();
  425. cout << "\n\rFin del listado !!!\n";
  426. cout << "\n\r<<< ... PRESIONE ENTER para continuar >>>";
  427. getch();
  428. return;
  429. }
  430.  
  431. void Encabezado1()
  432. {
  433. Raya58();
  434. cout << "\nCODIGO N O M B R E D I R E C C I O N TELEFONO TIPO";
  435. Raya60();
  436. }
  437.  
  438. void Raya58()
  439. {
  440. cout << "\n\r==============================================================================";
  441. }
  442.  
  443. void Raya60()
  444. {
  445. cout << "\n\r------------------------------------------------------------------------------";
  446. }
  447.  
  448. int Menu()
  449. {
  450. int i;
  451. do
  452. {
  453. system("cls");
  454. textcolor(LIGHTGREEN);
  455. cout << "\n\n\r Actualizacion de Clientes";
  456. textcolor(WHITE);
  457. cout << "\n\n\n\r 1.- ACTUALIZAR Nombre";
  458. cout << "\n\r 2.- ACTUALIZAR Direccion";
  459. cout << "\n\r 3.- ACTUALIZAR Tipo";
  460. textcolor(LIGHTRED);
  461. cout << "\n\r 0.- TERMINAR";
  462. textcolor(WHITE);
  463.  
  464. cout << "\n\n\n\r Seleccione su opcion ---> ";
  465. cin >> i;
  466. }while(i<0 || i>3);
  467. return(i);
  468. }
  469. void ordenarxcod(){
  470. FILE *F;
  471. CLIENTE A,B,aux;
  472. int i,j,n;
  473. F=fopen("Cliente.Sec","rb+");
  474. if(F==NULL){
  475. printf("No se puede abrir el archivo.\n");
  476. exit(1);
  477. }
  478. fseek(F,0,SEEK_END);
  479. n=ftell(F)/sizeof(A);
  480. for(i=0;i<=n-1;i++){
  481. for(j=i+1;j<=n;j++){
  482. fseek(F,i*sizeof(A),SEEK_SET);
  483. fread(&A,sizeof(A),1,F);
  484. fseek(F,j*sizeof(B),SEEK_SET);
  485. fread(&B,sizeof(B),1,F);
  486. if(strcmp(A.Cod,B.Cod)==1){
  487. aux=A;
  488. A=B;
  489. B=aux;
  490. fseek(F,i*sizeof(A),SEEK_SET);
  491. fwrite(&A,sizeof(A),1,F);
  492. fseek(F,j*sizeof(B),SEEK_SET);
  493. fwrite(&B,sizeof(B),1,F);
  494. }
  495. }
  496. }
  497. MostrarRegCLIENTE();
  498. }
  499. void ordenarxnom(){
  500. FILE *F;
  501. CLIENTE A,B,aux;
  502. int i,j,n;
  503. F=fopen("Cliente.Sec","rb+");
  504. if(F==NULL){
  505. printf("No se puede abrir el archivo.\n");
  506. exit(1);
  507. }
  508. fseek(F,0,SEEK_END);
  509. n=ftell(F)/sizeof(A);
  510. for(i=0;i<=n-1;i++){
  511. for(j=i+1;j<=n;j++){
  512. fseek(F,i*sizeof(A),SEEK_SET);
  513. fread(&A,sizeof(A),1,F);
  514. fseek(F,j*sizeof(B),SEEK_SET);
  515. fread(&B,sizeof(B),1,F);
  516. if(strcmp(A.Nombre,B.Nombre)==1){
  517. aux=A;
  518. A=B;
  519. B=aux;
  520. fseek(F,i*sizeof(A),SEEK_SET);
  521. fwrite(&A,sizeof(A),1,F);
  522. fseek(F,j*sizeof(B),SEEK_SET);
  523. fwrite(&B,sizeof(B),1,F);
  524. }
  525. }
  526. }
  527. MostrarRegCLIENTE();
  528. }
  529. void cuadro(int i,int j,int k,int l){
  530. register int a;
  531. for(a=j+1;a<l;a++){
  532. gotoxy(i,a);
  533. printf("%c",186);
  534. gotoxy(k,a);
  535. printf("%c",186);
  536. }
  537. for(a=i+1;a<k;a++){
  538. gotoxy(a,j);
  539. printf("%c",205);
  540. gotoxy(a,l);
  541. printf("%c",205);
  542. }
  543. gotoxy(i,j);printf("%c",201);
  544. gotoxy(k,j);printf("%c",187);
  545. gotoxy(i,l);printf("%c",200);
  546. gotoxy(k,l);printf("%c",188);
  547. gotoxy(1,1);
  548. }
10  Programación / Programación C/C++ / METODOS DE ORDENAMIENTO en: 12 Diciembre 2010, 05:34 am
HOLA TODOS LOS PROGRAMADORES ESPERO OBTENER BUENOS RESULTADOS Y HACER DISTINTAS AMISTADES E INFUNDIR EN ESTA RAMA , EN ESTA OPORTUNIDAD LES BRINDO UN TRABAJO HECHO EN BASE A LOS METODOS DE ORDENAMIENTO DE CAIRO , ESTAN TODOS ADAPTADOS Y LO ELEGANTE DE ESTE PROGRAMA ES QUE PUEDO SABER QUE METODO ES MAS RAPIDO PARA ELEMENTOS ALEATORIOS MAYORES DE 20000 Y ASI , ESPERO SUS OPINIONES Y COMENTARIOS ATTE, EL QUE DESEA MANDARME UN MENSAJE Y SE LO PUEDO FACILITAR O ALGUIEN ME PUEDE ORIENTAR COMO PUEDO COLGAR PROGRAMAS A ESTA PAGINA

ATTE : ANTON RAMIREZ , LEONARDO VLADIMIR  (ALUMNO UNI)

BUENO SI GUSTAN AQUI LES DEJO EL PSEUDOCIGO , SOLO ES CUESTION DE COMPILAR UTILIZO EL DEV-C++ , ESPERO COMENTARIOS :
Código
  1. /**
  2.  *Nombre del programa: METODOS DE ORDENAMIENTO
  3.  *Descripción: Este menu de ordenamiento contiene los 10 metodos de ordenamiento del libro de cairo ,aqui se podra mostrar
  4.  * cual es el mas rapido, cual es el mas lento .
  5.  * La forma que utilize para hallar el tiempo de cada ordenamiento para un mismo vector que tenga los mismos
  6.  * elementos aleatorios es ir al subprograma leerVector y poner en comentario a random cosa que siempre me
  7.  * va mostrar el mismo vector con los mismos elementos y por eso ya con el mismo vector generado siempre que
  8.  * compilo puedo distribuir el tiempo y saber quien es el mas rapido o mas lento.
  9.  *Autor: Anton ramirez,leonardo vladimir(20090231A)
  10.  *Fecha: 05/10/2010
  11.  *
  12.  */
  13.  
  14. #include <iostream>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <conio.h>
  18. #include <time.h>
  19. #define Max 120000
  20. #define TOPE 1000
  21. #define randomize (srand(time(0)))
  22. #define random(num) (rand()%(num))
  23.  
  24. using namespace std;
  25.  
  26. int METODODEORDENAMIENTO();
  27. void leerVector(int X[Max],int *dimX);
  28. void mostrarVector(int X[Max],int dimX);
  29. void ordenarxBurbuja(int X[Max],int dimX);
  30. void ordenarxBurbuja_senal(int X [Max],int *dimX);
  31. void ordenarxShaker_sort(int X[Max],int *dimX);
  32. void ordenarxInsercion_directa(int X[Max],int *dimX);
  33. void ordenarxInsercion_binaria(int X[Max],int *dimX);
  34. void ordenarxSeleccion_directa(int X[Max],int dimX);
  35. void ordenarxShell(int X[Max],int *dimX);
  36. void ordenarxQuicksort_recursivo(int X[Max],int *dimX);
  37. void Reduce_recursivo(int X[Max],int INI,int FIN);
  38. void ordenarxQuicksort_iterativo(int X[Max],int *dimX);
  39. int Reduce_iterativo(int X[Max],int INI,int FIN);
  40. void ordenarxHeapsort(int X[Max],int *dimX);
  41. void Inserta_monticulo(int X[Max],int *dimX);
  42. void Elimina_monticulo(int X[Max],int *dimX);
  43.  
  44. int main()
  45. {
  46. int Opcion,A[Max],na;
  47. do{
  48. Opcion = METODODEORDENAMIENTO();
  49. switch(Opcion)
  50. {
  51. case 1: {
  52. system("cls");
  53. printf("\n*******************Proceso de Lectura del Vector Aleatorio********************\n\n");
  54. leerVector(A,&na);
  55. system("pause");
  56. system("cls");
  57. break;
  58. }
  59. case 2: {
  60. system("cls");
  61. printf("\n****************Mostramos el Vector Aleatorio Generado***********************\n\n");
  62. mostrarVector(A,na);
  63. printf("\n\n");
  64. system("pause");
  65. system("cls");
  66. break;
  67. }
  68. case 3: {
  69. system("cls");
  70. printf("\n******************Ordenamiento por el Metodo de Burbuja************************\n\n");
  71. ordenarxBurbuja(A,na);
  72. printf("\n\n");
  73. system("pause");
  74. system("cls");
  75. break;
  76. }
  77. case 4: {
  78. system("cls");
  79. printf("\n**************Ordenamiento por el Metodo de Burbuja con Senal****************\n\n");
  80. ordenarxBurbuja_senal(A,&na);
  81. printf("\n\n");
  82. system("pause");
  83. system("cls");
  84. break;
  85. }
  86. case 5: {
  87. system("cls");
  88. printf("\n***************Ordenamiento por el Metodo de Shaker sort**********************\n\n");
  89. ordenarxShaker_sort(A,&na);
  90. printf("\n\n");
  91. system("pause");
  92. system("cls");
  93. break;
  94. }
  95. case 6: {
  96. system("cls");
  97. printf("\n***************Ordenamiento por el Metodo de Insercion Directa*****************\n\n");
  98. ordenarxInsercion_directa(A,&na);
  99. printf("\n\n");
  100. system("pause");
  101. system("cls");
  102. break;
  103. }
  104. case 7: {
  105. system("cls");
  106. printf("\n*******************Ordenamiento por el Metodo de Insercion Binaria************\n\n");
  107. ordenarxInsercion_binaria(A,&na);
  108. printf("\n\n");
  109. system("pause");
  110. system("cls");
  111. break;
  112. }
  113. case 8:{
  114. system("cls");
  115. printf("\n***************Ordenacion por el Metodo de Seleccion Directa******************\n\n");
  116. ordenarxSeleccion_directa(A,na);
  117. printf("\n\n");
  118. system("pause");
  119. system("cls");
  120. break;
  121. }
  122. case 9:{
  123. system("cls");
  124. printf("\n******************Ordenamiento por el Metodo de Shell**************************\n\n");
  125. ordenarxShell(A,&na);
  126. printf("\n\n");
  127. system("pause");
  128. system("cls");
  129. break;
  130. }
  131. case 10:{
  132. system("cls");
  133. printf("\n**************Ordenamiento por el Metodo Quicksort Recursivo*******************\n\n");
  134. ordenarxQuicksort_recursivo(A,&na);
  135. printf("\n\n");
  136. system("pause");
  137. system("cls");
  138. break;
  139. }
  140. case 11:{
  141. system("cls");
  142. printf("\n*************Ordenamiento por el Metodo Quicksort Iterativo*********************\n\n");
  143. ordenarxQuicksort_iterativo(A,&na);
  144. printf("\n\n");
  145. system("pause");
  146. system("cls");
  147. break;
  148. }
  149. case 12:{
  150. system("cls");
  151. printf("\n************************Ordenamiento por el Metodo del Monticulo****************\n\n");
  152. ordenarxHeapsort(A,&na);
  153. printf("\n\n");
  154. system("pause");
  155. system("cls");
  156. break;
  157. }
  158. }
  159. }while(Opcion != 0);
  160. return(0);
  161. }
  162.  
  163. int METODODEORDENAMIENTO()
  164. {
  165. int i;
  166. do
  167. {
  168. system("cls");
  169. printf("================================================================================\n");
  170. cout << "----------------M E T O D O S D E O R D E N A M I E N T O S-----------------";
  171. printf("================================================================================\n");
  172. cout << "\n ESCOJER EL MEJOR METODO PARA ORDENAR UN VECTOR: ";
  173. cout << "\n\n\r 0.- TERMINAR";
  174. cout << "\n\r 1.- LEER VECTOR ";
  175. cout << "\n\r 2.- MOSTRAR VECTOR ";
  176. cout << "\n\r 3.- ORDENAR X BURBUJA";
  177. cout << "\n\r 4.- ORDENAR X BURBUJA_SENAL";
  178. cout << "\n\r 5.- ORDENAR X SHAKER_SORT";
  179. cout << "\n\r 6.- ORDENAR X INSERCION_DIRECTA";
  180. cout << "\n\r 7.- ORDENAR X INSERCION_BINARIA";
  181. cout << "\n\r 8.- ORDENAR X SELECCION_DIRECTA";
  182. cout << "\n\r 9.- ORDENAR X SHELL";
  183. cout << "\n\r 10.- ORDENAR X QUICKSORT_RECURSIVO";
  184. cout << "\n\r 11.- ORDENAR X QUICKSORT_ITERATIVO";
  185. cout << "\n\r 12.- ORDENAR X HEAPSORT";
  186. cout << "\n\n\n\r Seleccione su opcion ---> ";
  187. cin >> i;
  188. }while(i<0 || i>12);
  189. return(i);
  190.  
  191. }
  192. void leerVector(int X[Max],int *dimX)
  193. {
  194. int n,i,val;
  195. randomize;//randomize es aqui donde si lo pongo como comentario me genera el mismo vector y es mas facil medir el tiempo..
  196. printf("INGRESE LA DIMENSION DE SU VECTOR A GENERAR: ");
  197. cin>>n;
  198. if(n<Max)
  199. {
  200. for(i=0;i<n;)
  201. {
  202. val=random(TOPE);
  203. X[i]=val;
  204. i=i+1;
  205. }
  206. *dimX=n;
  207. printf("\n............Proceso de Lectura de Numeros Aleatorios Completada............\n\n");
  208. }
  209. else
  210. {
  211. printf("Dimension fuera de Rango...\n\n");
  212. }
  213. }
  214.  
  215. void mostrarVector(int X[Max],int dimX)
  216. {
  217. int i,val;
  218. if(dimX>0){
  219. for(i=0;i<dimX;)
  220. {
  221. val=X[i];
  222. printf("%3d ",val);
  223. i=i+1;
  224. }
  225. }
  226. else{
  227. printf("Vector vacio ...!\n\n");
  228. }
  229. }
  230. void ordenarxBurbuja(int X[Max],int dimX)
  231. {
  232. int i,j,aux;
  233. long ini,fin;
  234. ini = clock();// INICIA EL PROCESO DEL ORDENAMIENTO
  235. for(int i=0;i<dimX-1;i++){
  236. for(int j=i+1;j<dimX;j++){
  237. if(X[i]>X[j]){
  238. aux=X[j];
  239. X[j]=X[i];
  240. X[i]=aux;
  241. }
  242. }
  243. }
  244. mostrarVector(X,dimX);
  245. fin=clock();
  246. printf("\n\ntiempo en segundos %f s\n\n",(fin-ini)/(float)CLOCKS_PER_SEC);
  247. }
  248.  
  249. void ordenarxBurbuja_senal(int X [Max],int *dimX)
  250. {
  251. bool BAND=false;
  252. int i=0,j,aux,
  253. N=*dimX-1;
  254. long ini,fin;
  255. ini = clock();
  256. while((i<=N-1)&&(!BAND))
  257. {
  258. BAND=true;
  259. for(j=0;j<=N-1;j++)
  260. {
  261. if(X[j]>X[j+1])
  262. {
  263. aux=X[j];
  264. X[j]=X[j+1];
  265. X[j+1]=aux;
  266. BAND=false;
  267. }
  268. }
  269. i=i+1;
  270. }
  271. mostrarVector(X,*dimX);
  272. fin=clock();
  273. printf("\n\ntiempo en segundos %f s\n\n",(fin-ini)/(float)CLOCKS_PER_SEC);
  274. }
  275.  
  276. void ordenarxShaker_sort(int X[Max],int *dimX)//METODO DE LA SACUDIDA
  277. {
  278. int i,IZQ=1,aux,N=*dimX-1,k=N,DER=N;
  279. long ini,fin;
  280. ini = clock();
  281. while(DER>=IZQ)
  282. {
  283. for(i=DER;i>=IZQ;i--)
  284. {
  285. if(X[i-1]>X[i])
  286. {
  287. aux=X[i-1];
  288. X[i-1]=X[i];
  289. X[i]=aux;
  290. k=i;
  291. }
  292. }
  293. IZQ=k+1;
  294. for(i=IZQ;i<=DER;i++)
  295. {
  296. if(X[i-1]>X[i])
  297. {
  298. aux=X[i-1];
  299. X[i-1]=X[i];
  300. X[i]=aux;
  301. k=i;
  302. }
  303. }
  304. DER=k-1;
  305. }
  306. mostrarVector(X,*dimX);
  307. fin=clock();
  308. printf("\n\ntiempo en segundos %f s\n\n",(fin-ini)/(float)CLOCKS_PER_SEC);
  309. }
  310.  
  311. void ordenarxInsercion_directa(int X[Max],int *dimX)
  312. {
  313. int i,aux,k,N=*dimX-1;
  314. long ini,fin;
  315. ini = clock();
  316. for(i=1;i<=N;i++)
  317. {
  318. aux=X[i];
  319. k=i-1;
  320. while((k>=0)&&(aux<X[k]))
  321. {
  322. X[k+1]=X[k];
  323. k=k-1;
  324. }
  325. X[k+1]=aux;
  326. }
  327. mostrarVector(X,*dimX);
  328. fin=clock();
  329. printf("\n\ntiempo en segundos %f s\n\n",(fin-ini)/(float)CLOCKS_PER_SEC);
  330. }
  331.  
  332. void ordenarxInsercion_binaria(int X[Max],int *dimX)
  333. {
  334. int i,aux,IZQ,DER,M,j,N=*dimX-1;
  335. long ini,fin;
  336. ini = clock();
  337. for(i=1;i<=N;i++)
  338. {
  339. aux=X[i];
  340. IZQ=0;
  341. DER=i-1;
  342. while(IZQ<=DER)
  343. {
  344. M=(int)((IZQ+DER)/2);
  345. if(aux<=X[M]){
  346. DER=M-1;
  347. }
  348. else
  349. {
  350. IZQ=M+1;
  351. }
  352. }
  353. j=i-1;
  354. while(j>=IZQ)
  355. {
  356. X[j+1]=X[j];
  357. j=j-1;
  358. }
  359. X[IZQ]=aux;
  360. }
  361. mostrarVector(X,*dimX);
  362. fin=clock();
  363. printf("\n\ntiempo en segundos %f s\n\n",(fin-ini)/(float)CLOCKS_PER_SEC);
  364. }
  365.  
  366. //ORDENAMIENTO POR SELECCION
  367. /*ESTE METODO CONSISTE EN ENCONTRAR EL MENOR ELEMENTO DEL ARREGLO
  368. Y UBICARLO AL PRINCIPIO... LUEGO SE BUSCA EL MENOR ELEMENTO DEL RESTO Y SE
  369. UBICA EN SEGUNDO LUGAR. SE REPITE EL PROCESO N-1 VECES*/
  370. void ordenarxSeleccion_directa(int X[Max],int dimX)
  371. {
  372. int i,MENOR,k,j;
  373. time_t ini,fin;
  374. ini = clock();// inicia el calculo del metodo de ordenamiento
  375.  
  376. for(i=0;i<dimX;)
  377. {
  378. MENOR=X[i];
  379. k=i;
  380. for(j=i+1;j<dimX;)
  381. {
  382. if(X[j]<MENOR)
  383. {
  384. MENOR=X[j];
  385. k=j;
  386. }
  387. j=j+1;
  388. }
  389. X[k]=X[i];
  390. X[i]=MENOR;
  391. i=i+1;
  392. }
  393. mostrarVector(X,dimX);
  394. fin=clock();
  395. printf("\n\ntiempo en segundos %f s\n\n",(fin-ini)/(double)CLOCKS_PER_SEC);
  396. }
  397.  
  398. void ordenarxShell(int X[Max],int *dimX)
  399. {
  400. int i,aux,N=*dimX-1,INT=N+1;
  401. bool BAND;
  402. long ini,fin;
  403. ini = clock();
  404. while(INT>0)
  405. {
  406. INT=(int)(INT/2);
  407. BAND=true;
  408. while(BAND)
  409. {
  410. BAND=false;
  411. i=0;
  412. while((i+INT)<=N)
  413. {
  414. if(X[i]>X[i+INT])
  415. {
  416. aux=X[i];
  417. X[i]=X[i+INT];
  418. X[i+INT]=aux;
  419. BAND=true;
  420. }
  421. i=i+1;
  422. }
  423. }
  424. }
  425. mostrarVector(X,*dimX);
  426. fin=clock();
  427. printf("\n\ntiempo en segundos %f s\n\n",(fin-ini)/(float)CLOCKS_PER_SEC);
  428. }
  429.  
  430. void ordenarxQuicksort_recursivo(int X[Max],int *dimX)
  431. {
  432. int N=*dimX-1;
  433. long ini,fin;
  434. ini = clock();
  435. Reduce_recursivo(X,0,N);
  436. mostrarVector(X,*dimX);
  437. fin=clock();
  438. printf("\n\ntiempo en segundos %f s\n\n",(fin-ini)/(float)CLOCKS_PER_SEC);
  439. }
  440.  
  441. void Reduce_recursivo(int X[Max],int INI,int FIN)
  442. {
  443. int IZQ=INI,DER=FIN,POS=INI,aux;
  444. bool BAND=true;
  445. while(BAND)
  446. {
  447. BAND=false;
  448. while((X[POS]<=X[DER])&&(POS!=DER))
  449. {
  450. DER=DER-1;
  451. }
  452. if(POS!=DER)
  453. {
  454. aux=X[POS];
  455. X[POS]=X[DER];
  456. X[DER]=aux;
  457. POS=DER;
  458. while((X[POS]>=X[IZQ])&&(POS!=IZQ))
  459. {
  460. IZQ=IZQ+1;
  461. }
  462. if(POS!=IZQ)
  463. {
  464. BAND=true;
  465. aux=X[POS];
  466. X[POS]=X[IZQ];
  467. X[IZQ]=aux;
  468. POS=IZQ;
  469. }
  470. }
  471. }
  472. if((POS-1)>INI)
  473. {
  474. Reduce_recursivo(X,INI,POS-1);
  475. }
  476. if(FIN>(POS+1))
  477. {
  478. Reduce_recursivo(X,POS+1,FIN);
  479. }
  480. }
  481. void ordenarxQuicksort_iterativo(int X[Max],int *dimX)
  482. {
  483. int full=0,I,F,POS,N=*dimX-1,P1[Max],P2[Max];
  484. long ini,fin;
  485. P1[full]=0;//PILA MENOR
  486. P2[full]=N;//PILA MAYOR
  487. ini = clock();
  488. while(full>=0)
  489. {
  490. I=P1[full];
  491. F=P2[full];
  492. full=full-1;
  493. POS=Reduce_iterativo(X,I,F);
  494. if(I<(POS-1))
  495. {
  496. full=full+1;
  497. P1[full]=I;
  498. P2[full]=POS-1;
  499. }
  500. if(F>(POS+1))
  501. {
  502. full=full+1;
  503. P1[full]=POS+1;
  504. P2[full]=F;
  505. }
  506. }
  507. mostrarVector(X,*dimX);
  508. fin=clock();
  509. printf("\n\ntiempo en segundos %f s\n\n",(fin-ini)/(float)CLOCKS_PER_SEC);
  510. }
  511.  
  512. int Reduce_iterativo(int X[Max],int INI,int FIN)
  513. {
  514. int IZQ=INI,DER=FIN,aux,POS=INI;
  515. bool BAND=true;
  516. while(BAND)
  517. {
  518. while((X[POS]<=X[DER])&&(POS!=DER))
  519. {
  520. DER=DER-1;
  521. }
  522. if(POS==DER)
  523. {
  524. BAND=false;
  525. }
  526. else
  527. {
  528. aux=X[POS];
  529. X[POS]=X[DER];
  530. X[DER]=aux;
  531. POS=DER;
  532. while((X[POS]>=X[IZQ])&&(POS!=IZQ))
  533. {
  534. IZQ=IZQ+1;
  535. }
  536. if(POS==IZQ)
  537. {
  538. BAND=false;
  539. }
  540. else
  541. {
  542. aux=X[POS];
  543. X[POS]=X[IZQ];
  544. X[IZQ]=aux;
  545. POS=IZQ;
  546. }
  547. }
  548. }
  549. //return(POS);// POS variable es una variable donde se almacena el resultado del algoritmo.
  550. }
  551.  
  552. void ordenarxHeapsort(int X[Max],int *dimX)//METODO DEL MONTICULO
  553. {//METODO EFICIENTE QUE TRABAJA CON ARBOLES .
  554. long ini,fin;
  555. ini = clock();
  556. Inserta_monticulo(X,dimX);
  557. Elimina_monticulo(X,dimX);
  558. mostrarVector(X,*dimX);
  559. fin=clock();
  560. printf("\n\ntiempo en segundos %f s\n\n",(fin-ini)/(float)CLOCKS_PER_SEC);
  561. }
  562.  
  563. void Inserta_monticulo(int X[Max],int *dimX)
  564. {
  565. int i,k,aux,N=*dimX-1;
  566. bool BAND;
  567. for(i=1;i<=N;i++)
  568. {
  569. k=i;
  570. BAND=true;
  571. while((k>0)&&BAND)
  572. {
  573. BAND=false;
  574. if(X[k]>X[(int)(k/2)])
  575. {
  576. aux=X[(int)(k/2)];
  577. X[(int)(k/2)]=X[k];
  578. X[k]=aux;
  579. k=(int)(k/2);
  580. BAND=true;
  581. }
  582. }
  583. }
  584. }
  585.  
  586. void Elimina_monticulo(int X[Max],int *dimX)
  587. {
  588. int i,aux,IZQ,DER,k,AP,MAYOR,N=*dimX-1;
  589. bool BOOL;
  590. for(i=N;i>=1;i--)
  591. {
  592. aux=X[i];
  593. X[i]=X[0];
  594. IZQ=1;
  595. DER=2;
  596. k=0;
  597. BOOL=true;
  598. while((IZQ<i)&&BOOL)
  599. {
  600. MAYOR=X[IZQ];
  601. AP=IZQ;
  602. if((MAYOR<X[DER])&&(DER!=i))
  603. {
  604. MAYOR=X[DER];
  605. AP=DER;
  606. }
  607. if(aux<MAYOR)
  608. {
  609. X[k]=X[AP];
  610. k=AP;
  611. }
  612. else
  613. {
  614. BOOL=false;
  615. }
  616. IZQ=k*2;
  617. DER=IZQ+1;
  618. }
  619. X[k]=aux;
  620. }
  621. }
Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines