Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bubble sort of structures using pointers in C

I want to sort an array of structures using the bubble sort algorithm and pointers in C. I have a cars structure:

typedef struct{
    char model[30];
    int hp;
    int price;
}cars;

and I allocate memory for 12 items:

cars *pointer = (cars*)malloc(12*sizeof(cars));

and read data from file:

for (i = 0; i <number ; i++) {
    fscanf(file, "%s %i %i\n", (pointer+i)->model, &(pointer+i)->hp, &(pointer+i)->price);
}

I pass pointer ptr to bubbleSort function:

bubbleSort(pointer, number);

Here is my bubbleSort function:

void bubbleSort(cars *x, int size) {
    int i, j;
    for (i=0;i<size-1;i++) {
    int swapped = 0;
    for (j = 0; j < size - 1 - i; j++) {
        if ( (x+i)->hp > (x+j+1)->hp ) {
            cars *temp = (x+j+1);
            x[j+1] = x[j];
            x[j] = *temp;
            swapped = 1;
        }
    }
        if (!swapped) {
        //return;
        }
    }
}

The problem is that I don't know how to swap items using pointers.

like image 503
yerassyl Avatar asked Apr 15 '15 20:04

yerassyl


1 Answers

Consider the following solution for sorting function:

void bubbleSort(cars *x, int size) 
{
    int i, j;
    for (i = 0; i < size-1; i++) 
    {
        for (j = 0; j < size-1-i; j++) 
        {
            if ( x[j].hp > x[j+1].hp ) 
            {
               cars temp = x[j+1];
               x[j+1] = x[j];
               x[j] = temp;
            }
        }
    }
}

The problem was in the data swap part

like image 148
VolAnd Avatar answered Oct 11 '22 06:10

VolAnd