[英]sorting array of structures using bubble sort - how to speed up exchange of struct members
我有一個由兩個元素char *word
和int number
組成的結構。 當我想使用冒泡排序對它們進行排序時,我必須為它們編寫交換部分:
int i,j,tmp;
char * temp;
for(i=0; i<max;i++)
{
for(j=0;j<max-i;j++)
{
if(strcmp(array[j].word,array[j+1].word)>0)
{
temp=array[j].word;
array[j].word=array[j+1].word;
array[j+1].word=temp;
tmp=array[j].number;
array[j].number=array[j+1].number;
array[j+1].number=tmp;
}
}
}
編輯我的結構聲明
typedef struct{
char *word;
int number;
}
words;
words *array=NULL;
如果我在數組中有n個元素怎么辦? 交換一切都是非常耗時的。 有沒有辦法省略這個?
OF COURSE除了我不想使用的其他排序算法(如qsort
)。
如果您關心的是交換過程中的性能,您應該考慮使用的結構類型的指針數組:
struct your_stuct *arr[MAX];
如果正確設置此數組,則交換將僅更改內存地址而不是結構內容,並且可以更快地運行:
在你的內循環中你應該使用:
struct your_struct *temp;
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
這就是你在問題中的意思嗎?
不是對structs
本身進行排序,而是創建一個指向結構的指針數組,以及一個適當的比較函數,它通過指針從結構中讀取適當的值,並對指針列表進行排序。 當然,所有額外的間接可能會掩蓋你從沒有實際交換結構所獲得的任何性能增益,因為你的結構相當小,但對於大型結構,這種方法很有意義。
int i, j, tmp;
words temp;
for (i = 0; i < max; i++)
{
for (j = 0; j < max - i; j++)
{
if (strcmp(array[j].word, array[j + 1].word) > 0)
{
memcpy(&temp, array[j], sizeof(words));
memcpy(array[j], array[j + 1], sizeof(words));
memcpy(array[j + 1], &temp, sizeof(words));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.