使用C中的指针冒泡排序结构

我想使用冒泡排序算法和C中的指针对结构数组进行排序。我有一个汽车结构:

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

我为12个项目分配内存:

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

并从文件中读取数据:

 for (i = 0; i model, &(pointer+i)->hp, &(pointer+i)->price); } 

我将指针ptr传递给bubbleSort函数:

 bubbleSort(pointer, number); 

这是我的bubbleSort函数:

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

问题是我不知道如何使用指针交换项目。

考虑以下用于排序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; } } } } 

问题出在数据交换部分

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

这是对此代码下的评论的回复; 它表明我建议的交换更少…… :)这里的代码:

 #include  #include  typedef struct { int x; int hp; } cars; int swaps; void bubbleSortB(cars *x, int size) { int i, j; cars temp; for (i=0;ihp > (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); } 

使用这样的交换函数:

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

或者这个,没有malloc:

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