I don't understand why the original array is sorted after calling the sorting function even though I used an alternate array. I first copied all the elements to avoid this problem. Any clarification would be welcome. Thank's.
#include <stdio.h>
void array_sort(int* t, int n)
{
int min, index;
int* p;
for (int i = 0; i < n; i++) { //to avoid changing the original array
*(p + i) = *(t + i);
}
for (int i = 0; i < n - 1; i++) {
min = *(p + i);
index = i;
for (int j = i + 1; j < n; j++) {
if (*(p + j) < min) {
min = *(p + j);
index = j;
}
}
*(p + index) = *(p + i);
*(p + i) = min;
}
for (int i = 0; i < n; i++)
printf("%i\t", *(p + i));
}
int main(void)
{
printf("Enter number of elements to be sorted : ");
int n;
scanf("%i", &n);
printf("\nEnter the numbers : ");
int p[n];
for (int i = 0; i < n; i++) {
scanf("%i", p + i);
}
array_sort(p, n);
printf("\n");
for (int i = 0; i < n; i++) { //check if original array is unsorted
printf("%i\t", *(p + i));
}
return 0;
}