my code stock.com

Merge sort, versão iterativa

Snippet options

Download: Download snippet as merge-sort.c.
Copy snippet: For this you need a free my code stock.com account.
Embed code : You will find the embed code for this snippet at the end of the page, if you want to embed it into a website or a blog!

#include <stdio.h>
/* 
 Implementacoes para merge sort, 
 versao recursiva mergesortR
 versao iterativa mergesortI
 htp://twitter.com/gccgomes
 */

#include <stdio.h>
#include <math.h>
//n tamanho do vetor!
//t tempo de inicio do programa

int mergeI(int l,int r,int u,int a[], int b[]){ //versao iterativa do merge com vetores
  int i,j,k;
  i=l; j=r; k=l;
  while (i<r && j<u) { 
    if (a[i]<=a[j]) {b[k]=a[i]; i++;} 
    else {b[k]=a[j]; j++;}
    k++;
  }
  while (i<r) { 
    b[k]=a[i]; i++; k++;
  }
  while (j<u) { 
    b[k]=a[j]; j++; k++;
  }
  for (k=l; k<u; k++) { 
    a[k]=b[k]; 
  }
}
MergeSortI(int a[], int b[], int n){  // versão iterativa do mergesort com vetores
  int k,u,i;
  k=1;
  while (k<n) {
    i=1;
    while (i+k<=n) {
      u=i+k*2;
      if (u>n) u=n+1;
      mergeI(i,i+k,u,a,b);
      i=i+k*2;
    }
    k=k*2;
  }
}
main(){ 
  int i;
  int a[100000],b[100000];

  for (i=1;i<=200;i++) 
    a[i]=random()%1000;
  MergeSortI(a,b,200);
  for (i=1;i<=200;i++) 
    printf("%d ",a[i]);
  printf("\n");

}

Create a free my code stock.com account now.

my code stok.com is a free service, which allows you to save and manage code snippes of any kind and programming language. We provide many advantages for your daily work with code-snippets, also for your teamwork. Give it a try!

Find out more and register now

You can customize the height of iFrame-Codes as needed! You can find more infos in our API Reference for iframe Embeds.