Skip to content

Instantly share code, notes, and snippets.

@lcmuniz
Last active October 20, 2024 23:19
Show Gist options
  • Save lcmuniz/7c11cc2ec400f513974cc48f1bf05427 to your computer and use it in GitHub Desktop.
Save lcmuniz/7c11cc2ec400f513974cc48f1bf05427 to your computer and use it in GitHub Desktop.
Função para ordenar um vetor em ordem crescente.
#include <stdio.h>
void ordena(int vetor[], int tamanho)
{
for (int i = 0; i < tamanho; i++)
{
for (int j = i; j < tamanho; j++)
{
if (vetor[i] > vetor[j])
{
int temp = vetor[i];
vetor[i] = vetor[j];
vetor[j] = temp;
}
}
}
}
void mostrarVetor(int vetor[], int tamanho)
{
for (int i = 0; i < tamanho; i++)
{
printf("%d ", vetor[i]);
}
}
int main()
{
int vetor[] = {5,6,2,4,3,1};
int tamanho = sizeof(vetor) / sizeof(int);
printf("Vetor antes da ordenação: ");
mostrarVetor(vetor, tamanho);
printf("\n");
ordena(vetor, tamanho);
printf("Vetor depois da ordenação: ");
mostrarVetor(vetor, tamanho);
printf("\n");
}
@ThonyFs
Copy link

ThonyFs commented Aug 26, 2022

for (int i = 0; i < tamanho - 1; i++)
{
for (int j = i; j < tamanho - 1; j++) // Se o tamanho aqui for - 1 o ultimo valor não entra na validação, retirando ele " - 1 " o codigo funciona perfeitamente.
{
if (vetor[i] > vetor[j])
{
int temp = vetor[i];
vetor[i] = vetor[j];
vetor[j] = temp;
}
}
}
}

@lcmuniz
Copy link
Author

lcmuniz commented Aug 26, 2022

for (int i = 0; i < tamanho - 1; i++) { for (int j = i; j < tamanho - 1; j++) // Se o tamanho aqui for - 1 o ultimo valor não entra na validação, retirando ele " - 1 " o codigo funciona perfeitamente. { if (vetor[i] > vetor[j]) { int temp = vetor[i]; vetor[i] = vetor[j]; vetor[j] = temp; } } } }

você tem razão. é que na versão anterior a comparação era i <= tamanho - 1 e mudou para i < tamanho e esqueci de tirar o -1. obg.

@ThonyFs
Copy link

ThonyFs commented Aug 29, 2022 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment