How to retain the unsorted Array in C after sorting

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How to retain the unsorted Array in C after sorting on this date .

Generally, i’m trying to get the run time of sorting algorithms in C using a randomly generated array. However, I think after the first sort, my function sorts the sorted array already and not the randomly generated array.

Here are examples of my code: For my array generation and printing

void generator(int A[], int n){
   int i;
    for(i = 0; i < n+1; i++){
      A[i] = rand()%n+1;
    }   
}

void printer(int A[], int n){
  for (int i = 0; i < n; ++i)
  {
    printf("%d ", A[i]);
  }
    printf("nn");
}

and My sorting:

void bubble(int A[], int n)
  int i,j;
  for (i = 0; i < n-1; i++ ){
    for(j = 0; j < n-i-1; j++){
      if(A[j] > A[j+1]){
        swap(&A[j], &A[j+1]);
      }
    }

now my main function is like this:

int main(){
 int n[] = {5} //this is an example array size, this could be extended
 for(int i = 0; i < 1; i++){
   int A[n[i]]; //this is were i initialize my array with the size of index i
   generator(A[n[i]], n);
   for(int j = 0; j < 10; j++){ //run sort 10x
     //printer(A, n);
     bubble(A,n);
}
}

I use the printer value above to check the array, but based on this code, on the first run, my sorting algorithm runs the randomly generated array, however on the 2nd to 10th run, it sorts the array that has been generated already.

Answer

Make a copy of the array and sort that.

Also, the n argument to all the other functions should be n[i].

int main(void){
    int n[] = {5} //this is an example array size, this could be extended
    for(int i = 0; i < 1; i++){
        int A[n[i]]; //this is were i initialize my array with the size of index i
        generator(A[n[i]], n[i]);
        for(int j = 0; j < 10; j++){ //run sort 10x
            int A_copy[n[i]];
            memcpy(A_copy, A, sizeof(A));
            bubble(A_copy, n[i]);
            printer(A_copy, n[i])
        }
    }
}