使用指向结构的指针实现冒泡排序
Implement Bubble Sort using a Pointer to Structure
结构是
struct student
{
char name[10];
int roll;
int percent;
};
struct student s[5];
struct student *p;
以上声明是全局的。这是我的冒泡排序功能。
void sort(int n)
{
int i,j,k;
struct student temp;
for(i=0;i<=(n-2);i++)
{
for(j=0;j<(n-i-1);j++){
if((p+j)->percent>(p+j+1)->percent){
//Define the temp variable of Structure type
temp=*(p+j);//Interchange s[j] and s[j+1]
*(p+j)=*(p+j+1);
*(p+j)=temp;
}
}
}
我想避免使用点运算符访问结构的元素
用于交换的临时变量已声明为结构类型。
此冒泡排序功能不起作用。这些是我认为我搞砸了的地方。错误请指出
if((p+j)->percent>(p+j+1)->percent){
temp=*(p+j);//Interchange s[j] and s[j+1]
*(p+j)=*(p+j+1);
*(p+j)=temp;
交换逻辑错误,先将temp设置为*(p+j),然后将*(p+j)设置为*(p+j+1),然后就写错了再次在 *(p+j) 上。我相信改变
*(p+j)=temp;
到
*(p+j+1)=temp;
应该修复它
一个明显的问题是你的交易逻辑:
if((p+j)->percent>(p+j+1)->percent){
temp=*(p+j);//Interchange s[j] and s[j+1]
*(p+j)=*(p+j+1);
*(p+j)=temp;
}
最后的赋值给了错误的元素,只不过是颠倒了之前的赋值。将其更改为:
if((p+j)->percent>(p+j+1)->percent){
temp=*(p+j);//Interchange s[j] and s[j+1]
*(p+j)=*(p+j+1);
*(p+j+1)=temp;
}
结构是
struct student
{
char name[10];
int roll;
int percent;
};
struct student s[5];
struct student *p;
以上声明是全局的。这是我的冒泡排序功能。
void sort(int n)
{
int i,j,k;
struct student temp;
for(i=0;i<=(n-2);i++)
{
for(j=0;j<(n-i-1);j++){
if((p+j)->percent>(p+j+1)->percent){
//Define the temp variable of Structure type
temp=*(p+j);//Interchange s[j] and s[j+1]
*(p+j)=*(p+j+1);
*(p+j)=temp;
}
}
}
我想避免使用点运算符访问结构的元素 用于交换的临时变量已声明为结构类型。 此冒泡排序功能不起作用。这些是我认为我搞砸了的地方。错误请指出
if((p+j)->percent>(p+j+1)->percent){
temp=*(p+j);//Interchange s[j] and s[j+1]
*(p+j)=*(p+j+1);
*(p+j)=temp;
交换逻辑错误,先将temp设置为*(p+j),然后将*(p+j)设置为*(p+j+1),然后就写错了再次在 *(p+j) 上。我相信改变
*(p+j)=temp;
到
*(p+j+1)=temp;
应该修复它
一个明显的问题是你的交易逻辑:
if((p+j)->percent>(p+j+1)->percent){
temp=*(p+j);//Interchange s[j] and s[j+1]
*(p+j)=*(p+j+1);
*(p+j)=temp;
}
最后的赋值给了错误的元素,只不过是颠倒了之前的赋值。将其更改为:
if((p+j)->percent>(p+j+1)->percent){
temp=*(p+j);//Interchange s[j] and s[j+1]
*(p+j)=*(p+j+1);
*(p+j+1)=temp;
}