我想使用气泡排序算法和C语言中的指针对结构数组进行排序。我有一个cars结构:
typedef struct{
char model[30];
int hp;
int price;
}cars;
我为12个项目分配了内存:
cars *pointer = (cars*)malloc(12*sizeof(cars));
并从文件中读取数据:
for (i = 0; i <number ; i++) {
fscanf(file, "%s %i %i\n", (pointer+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 < 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;
}
}
}
问题是我不知道如何使用指针交换项目。
考虑以下用于排序功能的解决方案:
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;
}
}
}
}
问题出在数据交换部分
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句