我想使用冒泡排序算法和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 %dn",swaps); swaps=0; bubbleSortB(y,10); //My sort for(i=0;i<10;i++) printf("%d ",y[i].hp); printf("- swaps %dn",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; }
以上就是c/c++开发分享使用C中的指针冒泡排序结构相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/555215.html