victorialais

bubble sort

Jun 4th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. /* Algoritmo de ordenação Bubble Sort */
  2.  
  3. #include <stdio.h>
  4.  
  5.   /* Definição da função bubble_sort */
  6.   void bubble_sort (int vet[], int max) {      
  7.     int flag, i, aux;  
  8.    
  9.     do {
  10.       flag = 0;
  11.       for (i = 0; i < (max - 1); i++) {
  12.    
  13.    /* Verfica se o vetor está em ordem, no caso ele coloca em ordem crescente, para decrescente trocar '>' por '<' */
  14.    if (vet[i] > vet[i+1]) {
  15.      /* Caso não esteja, ordena */
  16.      aux = vet[i];
  17.      vet[i] = vet[i+1];
  18.      vet[i+1] = aux;
  19.      flag =1;
  20.    }
  21.       }
  22.     /* Repete enquanto algum valor estiver fora de ordem */  
  23.     } while (flag == 1);
  24.    
  25.     /* Imprime o vetor ordenado em ordem crescente */
  26.     for (i = 0; i < max; i++) {
  27.       printf ("%d ",vet[i]);
  28.     }
  29.     printf ("\n");
  30.   }
  31.  
  32. main () {
  33.   int max, i;
  34.  
  35.   /* Lê o total de números do vetor */
  36.   scanf ("%d", &max);
  37.  
  38.   /* Define o vetor com o número max de algarismos */
  39.   int vetor[max];
  40.  
  41.   for (i = 0; i < max; i++) {
  42.     /* Lê cada indice do vetor */
  43.     scanf ("%d",&vetor[i]);
  44.   }
  45.  
  46.   /* Dentro dessa função o vetor será ordenado */
  47.   bubble_sort (vetor, max);
  48.  
  49. }
Advertisement
Add Comment
Please, Sign In to add comment