Bubble structures using pointers in C

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

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

and I allocate memory for 12 elements:

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

and read data from a file:

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

I pass the 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 do not know how to change elements using pointers.

+6
source share
3 answers

Consider the following solution for the sort 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 data exchange.

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

This is the response to the comment in this code; it shows that the sorting I suggest is swap less ... :) Here is the code:

 #include <stdio.h> #include <string.h> typedef struct { int x; int hp; } cars; int swaps; void bubbleSortB(cars *x, int size) { int i, j; cars temp; for (i=0;i<size-1;i++) { for (j = i+1; j < size; j++) { if ( (x+i)->hp > (x+j)->hp ) { temp = x[j]; x[j] = x[i]; x[i] = temp; swaps++; } } } } void bubbleSortA(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; swaps++; } } } } int main(void) { int i; cars x[10]={ {1,4},{1,8},{1,12},{1,6},{1,5},{1,4},{1,8},{1,12},{1,6},{1,5} }; cars y[10]={ {1,4},{1,8},{1,12},{1,6},{1,5},{1,4},{1,8},{1,12},{1,6},{1,5} }; swaps=0; bubbleSortA(x,10); for(i=0;i<10;i++) printf("%d ",x[i].hp); printf("- swaps %d\n",swaps); swaps=0; bubbleSortB(y,10); //My sort for(i=0;i<10;i++) printf("%d ",y[i].hp); printf("- swaps %d\n",swaps); } 
0
source

Use the swap function, for example:

 #define TYPE <your type> void swap(TYPE *a, TYPE *b){ TYPE *temp = (TYPE*)malloc(sizeof(TYPE)); *temp = *a; *a = *b; *b = *temp; free(temp); } 

Or this one, without malloc:

 void swap(TYPE *a, TYPE *b){ TYPE temp; temp = *a; *a = *b; *b = temp; } 
-1
source

Source: https://habr.com/ru/post/985213/


All Articles