Issue
I need to sort elements of array in ascending order using selection sort algorithm and pointer arithmetic.
That means the following (using pointer arithmetic):
- find the minimum element in unsorted array;
- swap the found minimum element with the first element
- repeat it until the end of array
- print sorted array
Code:
#include <stdio.h>
void swap(double **pp, double **qq) {
double *temp = *pp;
*pp = *qq;
*qq = temp;
}
void sortArray(double arr[], int n) {
double *q, *min;
q = min = arr;
while (min > arr + n) {
while (q < arr + n) {
if (*q < *min)
min = q;
q++;
}
min++;
swap(&min, &q);
}
}
void writeSorted(double arr[], int n) {
double *qq = arr;
while (qq < arr + n) {
printf("%g ", *qq);
qq++;
}
}
int main() {
double arr[4] = {2.1, 4.23, 3.67, 1.5};
int n = 4;
sortArray(arr, n);
writeSorted(arr, n);
return 0;
}
This code prints the same unsorted array. Do you know how to fix it?
Solution
There is an error about the role of swap: you have to swap the elements, not the corresponding pointers.
Moreover, there is a confusion about definition and role of each pointer.
In particular, it is important to keep trace of the pointer to the start of next iteration.
#include <stdio.h>
void swap(double *pp, double *qq) {
double temp = *pp;
*pp = *qq;
*qq = temp;
}
void sortArray(double arr[], size_t n) {
double *start = arr;
while (start < arr + n) {
double *q = start + 1;
double *min = start;
while (q < arr + n) {
if (*q < *min) min = q;
q++;
}
swap (start, min);
start++;
}
}
void writeArray(double arr[], size_t n) {
double *qq = arr;
while (qq < arr + n) {
printf("%g ", *qq);
qq++;
}
printf ("\n");
}
int main() {
double arr[] = {2.1, 4.23, 3.67, 1.5};
size_t n = sizeof(arr)/sizeof(*arr);
writeArray (arr, n);
sortArray(arr, n);
writeArray(arr, n);
return 0;
}
Besides, I don’t know what are exactly your constraints for this exercise. Even by using pointers, some simplifications are possible. For example, for the print function:
void writeArray(double arr[], size_t n) {
while (n--) {
printf("%g ", *arr++);
}
printf ("\n");
}
Answered By – Damien
Answer Checked By – Marilyn (BugsFixing Volunteer)