Reputation: 51
I've tried a couple times, and I cannot get my for loop to progress more than one iteration. The project requires me to use pointer variables as an argument for a bubble sort program. I am not including the whole code (ie. I'm omitting the input array and the print operation since the problem exists within the bubble sort code itself).
I've tried various versions of this same code as well as imputing print options at various areas in my code. This has made me realize that my value for my pointer variable "i" immediately exceeds the largest address in my array. For some reasons, the array addresses are being taken as a negative value. I am unsure how to resolve this.
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
int n = ARRAY_SIZE(arr);
bubbleSort(arr, n);
[SKIPPING CODE, ARRAY SIZE IS 7]
void bubbleSort(int *arr, int n) {
int *i, q;
if (n == 1) {
return;
} else {
for (i = arr; i < (arr + n); i++) {
if (*arr > *(arr + 1)) {
printf("This: %d, also value of i: %d \n", *arr, *i);
swap(*arr, *(arr + 1));
printf("This: %d, that %d, and i: %d \n", arr, (arr + n), i);
}
}
q = n - 1;
bubbleSort(arr, q);
}
}
From the first print statement, I have that the value of "*arr" and "*i" are both 64. I had tried before to see the values of *arr and *arr + 1 after the swap function and they were correct (34 and 64 respectively).
The second print function indicates that i and arr both equal "-13312" and arr + n is equal to "-13284."
My print function, which is not listed here, just prints out seven 34s in a row.
Upvotes: 1
Views: 75
Reputation: 144695
The code is broken in multiple ways:
i < (arr + n - 1)
You should use i
instead of arr
in the loop body:
for (i = arr; i < arr + n - 1; i++) {
if (*i > *(i + 1)) {
swap(*i, *(i + 1));
}
}
Naming a pointer i
and a length q
is asking for trouble. i
is typically use for an index variable and the algorithm can be written this way:
void bubbleSort(int *arr, int n) {
for (; n > 1; n--) {
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
}
}
Upvotes: 2