[英]Bubble sort of structures using pointers in C
我想使用冒泡排序算法和C中的指針對結構數組進行排序。我有一個汽車結構:
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;
}
}
}
}
問題出在數據交換部分
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;
}
}
}
}
這是對此代碼下的評論的回復; 它表明我建議的交換更少...... :)這里的代碼:
#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);
}
使用這樣的交換函數:
#define TYPE <your 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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.