0

I got a problem. I need to sort an array in different ways. The problem is that after I sort it the first time my original array stays sorted. I tried copying the original array to another one but it remains sorted. My code is the following:


void printArray(int ** array, int n){
    int i;
    for(i = 0; i < n; i++){
        printf(" %d ", (*array)[i]);
    }
}

int main(){
    int *array, n, number, i, j;

    printf("\nIntroduce the size of the array:");
    scanf("%d", &n);
    array = (int*)malloc(n * sizeof(int));
    for(i = 0; i < n; i++){
        number = rand() % 1000 + 1;
        array[i] = number;
    }

    printf("\nUnsorted array:");
    printArray(&array, n);

    //bubble sort
    int *array2, aux;
    array2 = array;
    for (i = 0; i < n-1; i++){
        for (j = 0; j < n-1; j++){
            if(array2[j] > array2[j+1]){
                aux = array2[j];
                array2[j] = array2[j+1];
                array2[j+1] = aux;
            }
        }
    }
    printf("\nSorted array:");
    printArray(&array2, n);         

    //The problem is in here, if I print the original array, it's already sorted
    printf("\nUnsorted original array:");
    printArray(&array, n);

}

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

3 Answers3

1

This happens because you just assign another pointer (array) variable to the same address in memory, so you sort the initial array.

What you have to do is to allocate memory and copy the array before you sort it. You can do it very similar to your printArray() routine:

void copyArray(int *old_array, int *new_array, int n){
    int i;
    for(i = 0; i < n; i++){
        new_array[i] = old_array[i];
    }
}

Then in your main() you do:

array2 = (int*)malloc(n * sizeof(int));
copyArray(array, array2, n);
Anatoliy R
  • 1,749
  • 2
  • 14
  • 20
1

Instead of

array2 = array;

Do this

array2 = (int*)malloc(n * sizeof(int));
for(i = 0; i < n; i++){
     array2[i] = array[i];
}
thisisjaymehta
  • 614
  • 1
  • 12
  • 26
0

See, you are actually creating only one array. Initially you used pointer variable "array" to point to the base address of this array. Then by doing this,

array2 = array;

you copied the base address of the array(that was stored in the pointer variable "array") to a pointer variable "array2", and using this "array2" pointer variable you sorted the original(and only) array.

To have both the sorted and the unsorted arrays you need to copy the original array and then sort any one of them. To create a copy of the original array:

int *newArray=(int*)malloc(sizeof(int));    // dynamically allocating memory
for(i=0;i<n;i++){
newArray[i]=array[i];              // *(newArray+i)=*(array+i); alternative
}
iashek
  • 31
  • 1
  • 8