Created
November 30, 2023 01:27
-
-
Save divanibarbosa/b1c3efe88fbd354c447b78087f1c790e to your computer and use it in GitHub Desktop.
Ordenação MergeSort em C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Criado por: profa. Divani Barbosa Gavinier | |
// Curriculo Lattes: http://lattes.cnpq.br/8503400830635447 | |
// divanibarbosa@gmail.com | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
#define n 10000 | |
int v[n]; | |
void intercala(int inicio, int meio, int fim) { | |
int aux[fim-inicio+1]; | |
int i = inicio; | |
int j = meio+1; | |
int k = 0; | |
while ( i<=meio && j<=fim ) | |
if ( v[i] <= v[j] ) aux[k++] = v[i++]; | |
else aux[k++] = v[j++]; | |
while ( i <= meio ) aux[k++] = v[i++]; | |
while ( j <= fim ) aux[k++] = v[j++]; | |
for ( i=0; i<(fim-inicio+1); i++) v[inicio + i] = aux[i]; | |
} | |
void MergeSort(int inicio, int fim) { | |
if(inicio==fim) return; | |
int meio=(inicio+fim)/2; | |
MergeSort(inicio,meio); | |
MergeSort(meio+1,fim); | |
intercala(inicio,meio,fim); | |
} | |
int main() { | |
int i; | |
clock_t inicio, fim; /* variáveis inicio e fim do tipo clock_t usadas em contagem de tempo */ | |
srand(time(NULL)); | |
printf("Conteudo vetor de %d itens:\n",n); | |
for(i=0; i<n; i++) { | |
v[i] = rand()%1000; | |
printf("%d ",v[i]); | |
} | |
inicio = clock(); // inicia contagem do tempo | |
MergeSort(0,n); | |
fim = clock(); // finaliza a contagem de tempo | |
printf("\nConteudo vetor depois ordenacao:\n"); | |
for(i=0; i<n; i++) { | |
printf("%d ",v[i]); | |
} | |
printf("\nTempo gasto ordenacao MergeSort: %f segundos.\n\n",(float)(fim - inicio)/CLOCKS_PER_SEC); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment