DEV Community

Leo
Leo

Posted on

Merge

#include <iostream>

int *arreglo (int n){
  int *a = new int[n];
  for (int i=0; i<n; i++) a[i] = rand() % (n*10) + 1;
  return a;
}

void print(int *a, int n){
  for (int i=0; i<n; i++)
    std::cout << a[i] << " ";
}

void swap(int &a, int &b){
  int c = a;
  a = b;
  b = c;
}

int max(int *a, int n){
  int m = 0;
  int i = 1;
  while (i < n){
    if (a[m] < a[i]) m = i;
  }
  return m;
}

void selection(int *a, int n){
  for (int k = n-1; k > 0; k--){
    swap(a[max(a,k)], a[k]);
  }
}

void bsort (int *a, int n){
  for (int k = n - 1; k > 0; k--)
    for(int i = 0; i < k; i++)
      if (a[i] > a[i+1]) swap(a[i], a[i+1]);
}

int *merge(int *a, int n, int *b, int m){

  int *c = new int[n+m];
  int i = 0, j = 0, k = 0;
  while (i < n && j < m) c[k++] = a[i] < b[j] ? a[i++] : b[j++];

    while (i < n) c[k++] = a[i++];
    while (j < m) c[k++] = b[j++];

  return c;
}

int main() {
  srand((unsigned)time(nullptr));

  int min = 20;
  int max = 50;
  int n = rand() % (max - (min - 1)) + min;
  int m = rand() % (max - (min - 1)) + min;

  int *a = arreglo(n);
  int *b = arreglo(m);

  bsort(a,n);
  bsort(b,m);

  printf("a: ");
  print(a,n);

  printf("\nb: ");
  print(b,m);

  int *c = merge(a,n,b,m);

  printf("\nc: ");
  print(c,n+m);

  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)