DEV Community

Leo
Leo

Posted on

Disorder (scramble algorithm)

#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] << " ";
  printf("\n");
}

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

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]);
}

void shuffle(int *a, int n){
  for (int k = n - 1; k > 0; k--)
    swap(a[rand() % (k + 1)], a[k]);  
}

int main(){

srand((unsigned) time(nullptr));

int n = 10;
int *a = arreglo(n);
print(a,n);
  printf("\n");
for (int i = 0; i < 24; i++){

shuffle(a,n);
print(a,n);

  }
delete [] a;
return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)