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?
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");
}
Related
I'm really newbie to c programing, and I have no idea how can I make it work.
I want to make sort function that sorting array of integers by using 2 argument.
I want to use recursive on sort function. and sorting from end of array to first. by ascending order.
void ft_sorting(int *arr, int size);
but I don't know what went wrong. It totally out of my understanding with pointer and array. right now I really have no idea. Can some one pointing what I did wrong. And what I need to learn and fix. Thank you!
void ft_recure(int *a, int *b, int j, int k)
{
if (--j >= 0)
{
if (a[k] < b[j])
{
a[k] = b[j];
}
else
{
ft_recure(a[k], b[j], j, k);
}
}
else
return a[k];
}
void ft_sort(int *tab, int size)
{
int i;
int h;
while (size > 0)
{
i = size;
h = i;
tab[size] = ft_recure(tab, tab, i, h);
size--;
}
}
and also I try this.
int ft_recurs(int x, int y, int a, int b)
{
int j;
j = a;
if( a > 0)
{
if(*x < *(y - 1);)
{
b = *(y - 1);
*x = b;
}
ft_recurs(*x,*(y - 1),a - 1, b);
}
else
{
return *x;
}
}
void ft_sort_int_tab(int *tab, int size)
{
int memo;
int i;
while(--size >= 0)
{
i = size;
tab[size] = ft_recurs(tab[i], tab[size], i, memo);
}
}
In the first approach, you did improper when calling API again:
void ft_recure(int *a, int *b, int j, int k)
{
if (--j >= 0)
{
if (a[k] < b[j])
{
a[k] = b[j];
}
else
{
ft_recure(a[k], b[j], j, k);
}
}
else
return a[k];
}
a and b input to API ft_recure is a pointer but in ft_recure(a[k], b[j], j, k); it is value. You should correct this as: ft_recure(&a[k], &b[j], j, k); if you expect to input the address of k and j elements.
In your alternative usage:
int ft_recurs(int x, int y, int a, int b)
{
int j;
j = a;
if( a > 0)
{
if(*x < *(y - 1);)
{
b = *(y - 1);
*x = b;
}
ft_recurs(*x,*(y - 1),a - 1, b);
}
else
{
return *x;
}
}
The input is value but in the function you are using *x andn *(y-1) is not really a proper way. May be you could try int ft_recurs(int x[], int y[], int a, int b). But if so, you also need to provide pointer address at ft_recurs(*x,*(y - 1),a - 1, b); and then the issue come back to similar to first approach.
I tried to build a heap and finally print the elements in the form of an array.
Here it is the code (I know this doesn't really make sense but I just wanted to test my knowlwdge of heap and dynamic arrays):
#include <stdio.h>
#include <stdlib.h>
void heapiify(int *arr,int n, int i)
{
int largest=i;
int l=2*i+1; // left node
int r= 2*i+2; // right node
if(l<=n && *arr[l]>=*arr[i])
largest=l;
if (r <=n && *arr[r]<=*arr[i])
largest= r;
if(largest !=i)
{
int temp=*arr[i];
*arr[i]=*arr[largest];
*arr[largest]=temp;
}
heapify(*arr,n,largest);
}
void buildh(int *arr,int n,int r,int c)
{
int i;
for(i=n/2-1;i>=0;i--)
heapify(*arr,n,i);
output(*arr,r,c);
}
void output(int *arr,int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d",*arr[i*c+j]);
}
printf("\n");
}
}
int main()
{
int i,j,r,c;
printf("enter the number of rows");
scanf("%d",&r);
printf("enter the number of columns");
scanf("%d",&c);
int n=r*c;
int *arr=malloc(n*sizeof(int));
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf("%d",&arr[i*c+j]);
}
buildh(*arr,n,r,c);
}
I'm getting 9 errors which are all the same
invalid argument type of unary '*'( have int)
Your arr variable is of type pointer to int:
int *arr=malloc(n*sizeof(int));
So when you call buildh, which takes the same type, you have to pass it as-is:
buildh(arr,n,r,c);
Same for the other cases.
The problem is the dereference of arr, across your funtions in multiple places, and the passing of dereferenced *arr in your functions to int * parameters, you should pass arr, try:
//...
void heapify(int *arr, int n, int i)
{
int largest = i;
int l = 2 * i + 1; // left node
int r = 2 * i + 2; // right node
if (l <= n && arr[l] >= arr[i]) //here
largest = l;
if (r <= n && arr[r] <= arr[i]) //here
largest = r;
if (largest != i)
{
int temp = arr[i]; //here
arr[i] = arr[largest]; //here
arr[largest] = temp; //here
}
heapify(arr, n, largest); //here
}
void buildh(int *arr, int n, int r, int c)
{
int i;
for (i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i); //here
output(arr, r, c); //here
}
void output(int *arr, int r, int c)
{
int i, j;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
printf("%d", arr[i * c + j]); //here
}
printf("\n");
}
}
int main()
{
//...
buildh(arr, n, r, c); //here
}
I am trying to sort an array from least to greatest using pointers instead of array subscripts. I am not sure where the problem is but when i run this code, the values are returned in the same order that they were entered. The find_largest and swap functions both do exactly what they say. The selection_sort function uses a for loop to sort the numbers from right to left (greatest to smallest, right to left). I have been staring at this for a while now and it looks like it should work fine but like i said, for some reason the numbers are returned in the same order they were entered.
Here is my code:
#include <stdio.h>
#define N 5
void selection_sort(int *a, int n);
int *find_largest(int *a, int n);
void swap(int *p, int *q);
int main(void)
{
int i;
int a[N];
printf("Enter %d numbers to be sorted: ", N);
for (i = 0; i < N; i++)
scanf("%d", (a+i));
selection_sort(a, N);
printf("In sorted order:");
for (i = 0; i < N; i++)
printf(" %d", *(a+i));
printf("\n");
return 0;
}
void selection_sort(int *a, int n)
{
int i = 0;
int *largest;
for(i = 0; i < n; i++){
largest = find_largest(a, n-i);
swap(largest, a+(n-1-i));
}
}
int *find_largest(int *a, int n){
int *p = a;
int *largest = p;
for(p = a; p < a+n-1; p++){
if(*(p+1) > *p){
largest = (p + 1);
}
}
return largest;
}
void swap(int *p, int *q){
int *temp;
temp = p;
p = q;
q = temp;
}
There are two mistakes in your code.
One, logical in the find_largest function:
int *find_largest(int *a, int n){
int *p = a;
int *largest = p;
for(p = a; p < a+n-1; p++){
if(*(p+1) > *largest){ <---- //here you were checking for *(p)
largest = (p + 1);
}
}
return largest;
}
the other is with pointers in swap function:
void swap(int *p, int *q){
int temp;
temp = *p;
*p = *q;
*q = temp;
}
As John Bollinger mentioned in the comments, swap() does not function correctly - all it does is reassign pointers that quickly go out of scope.
Here is a rewrite of that function that does work. Just swap it in and it fits perfectly.
void swap(int *p, int *q){
int temp;
temp = *p;
*p = *q;
*q = temp;
}
Thanks to John Bollinger.
This program is supposed to take an array, and sort it from lowest to highest value. My program won't sort any values though. I believe the error is in the selectionSort. The values i and j are present in the function, I printed them out inside the function but they are not passed into the swap function. I tried making i and j pointers but it didn't work. I just have no clue on what to do next. Any help would be appreciated.
#include <stdio.h>
#define N 5
void selectionSort(int *a, int n);
int *findLargest(int *a, int n);
void swap(int *p, int *q);
int main(void)
{
int i;
int a[N];
printf("Enter %d numbers: ", N);
for (i = 0; i < N; i++) {
scanf("%d", &a[i]);
}
selectionSort(a, N);
printf("In sorted order:");
for (i = 0; i < N; i++) {
printf(" %d", a[i]);
}
printf("\n");
return 0;
}
void selectionSort(int *a, int n)
{
int *p = a;
int i;
int j;
if (n == 1) {
return;
}
i = *(p+n-1);
j = *findLargest(a, n);
swap(&i, &j);
selectionSort(a, n - 1);
}
int *findLargest(int *a, int n)
{
int *p;
int *p_max = a;
for(p = a + 1; p < a + n - 1; p++) {
if ( *p > *p_max)
p_max = p;
}
return p_max;
}
void swap(int *p, int *q)
{
int temp = *(p-1);
*(p-1) = *q;
*q = temp;
}
The problem is in your call of swap: you swap the content of two local variables
int i;
int j;
... // Some other code, then
swap(&i, &j);
This has no effect on the original array. You should be passing p+n-1 and findLargest(a, n) directly, or store their results in pointers, not in ints:
swap(p+n-1, findLargest(a, n));
In addition, your swap is broken: rather than swapping the content of two pointers, it assumes that p points one element past the target location. This is a bad assumption to make in a general-purpose function, such as swap, and it also leads to undefined behavior in your program.
void swap(int *p, int *q) {
int temp = *p;
*p = *q;
*q = temp;
}
I don't know yet what is the problem with the code:
#include <stdio.h>
#define cutoff 3
int swap(int *x, int *y)
{
int *tmp;
tmp = x;
x = y;
y = tmp;
return *x, *y;
}
void qsort(int a[], int left, int right)
{
int i, j;
int pivot;
if (left + cutoff <= right) // JUST TO ENSURE THAT THE ARRAY'S SIZE IS >= CUTOFF.
{
pivot = median(a, left, right);
i = left;
j = right - 1;
for (;;)
{
while (a[i] < pivot)
i++;
while (a[j] > pivot)
j--;
if (i < j)
swap(&a[i], &a[j]);
else
break;
}
swap(&a[i], &a[right - 1]); // RESTORE PIVOT
qsort(a, left, i-1);
qsort(a, i+1, right);
}
//else
// PERFORM INSERTION SORT
}
void quicksort(int a[], int n)
{
int i;
qsort(a, 0, n - 1);
printf("THE SORTED ARRAY IS: ");
for(i=0;i<n;i++)
printf("%d ", a[i]);
}
int median(int a[], int left, int right)
{
int center = (left + right) / 2;
if(a[left] > a[center])
swap(&a[left], &a[center]);
if(a[left] > a[right])
swap(&a[left], &a[right]);
if(a[center] > a[right])
swap(&a[center], &a[right]);
swap(&a[center], &a[right - 1]); // HIDE PIVOT.
return a[right - 1]; // RETURN PIVOT.
}
void main()
{
int a[100], i, n;
printf("ENTER THE SIZE: ");
scanf("%d", &n);
printf("ENTER THE UNSORTED ARRAY: ");
for (i=0;i<n;i++)
scanf("%d", &a[i]);
quicksort(a, n);
}
The output is the same as teh input and soemtimes it is taking more than the input size. I think that the problem lies in the median function, choosing the pivot.
int swap(int *x, int *y)
{
int *tmp;
tmp = x;
x = y;
y = tmp;
return *x, *y;
}
You're assigning the pointers, not their values. Use this instead
void swap(int *x, int *y)
{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
Also, the return means nothing since the values are swapped by the pointers, and you cannot also return 2 values at a time. The return type should be void like #Yu Hao said
The main problem is in your swap() function
int swap(int *x, int *y)
{
int *tmp;
tmp = x;
x = y;
y = tmp;
return *x, *y;
}
It only swaps the value of the pointer x and y themselves, but not the value that x and y points. Remember that functions in C are always pass-by-value. You need to swap *x and *y.
void swap(int *x, int *y)
{
int tmp;
tmp = x;
*x = *y;
*y = tmp;
}