PDA

View Full Version : سوال: مرتب کردن لیست پیوندی به روش انتخابی و حبابی



salman.ba
دوشنبه 04 بهمن 1389, 01:02 صبح
با سلام
من یه برنامه نوشتم که 10 عدد رو می گیره و تو یه لیست پیوندی یک طرفه قرار می ده ، اونوقت لیست پیوندی رو به یکی از روش های انتخابی یا حبابی مرتب می کنه و نمایش می ده،ولی نمی دونم چرا عددهام درست sort نمی شن.
ممنون می شم اگه راهنماییم کنید.




#include <iostream.h>
#include <conio.h>
#include <stdlib.h>

class list;
class node
{
friend class list;
private:
int data;
node *link;
};
class list
{
private:
node *first;
public:
int retrieve(int loc)
{
node *cur=first;
for (int i=1;i<loc;i++)
cur=cur->link;
return (cur->data);
}
void swap(int loc1,int loc2)
{
node *node1=first;
node *node2=first;
for (int i=1;i<loc1;i++)
node1=node1->link;
for (int j=1;j<loc2;j++)
node2=node2->link;
int temp=node1->data;
node1->data=node2->data;
node2->data=temp;
}
void addfirst(int a)
{
node *p=new node();
p->data=a;
p->link=first;
first=p;
}
void print()
{
for (node *q=first;q->link!=0;q=q->link)
cout<<q->data<<"\t";
}

void SelectionSort()
{
for (int i=10;i<1;i--)
{
int maxsize=1;
for (int j=2;j<=i;j++)
{
if ((retrieve(maxsize))<(retrieve(j)))
maxsize=j;
}
swap(i,maxsize);
}
}
void BubbleSort()
{
for (int i=2;i<11;i++)
{
for (int j=1;j<i;j++)
{
if((retrieve(j))>(retrieve(j+1)))
swap(j,(j+1));
}
}
}
};
void menu();
int main()
{
menu();
getch();
return 0;
}
void menu()
{
list mylist;
int t,n[9],s,a;
cout<<"\n\t\t\tThis program will sort 10 numbers\n\n";
for(int i=1;i<11;i++)
{
cout<<"Please enter number"<<i<<":\t";
cin>>t;
mylist.addfirst(t);
n[i-1]=t;
}
cout<<"\n\nSelect a Sort Algorithm:\n\n"<<"\t1.Selection Sort <1>\n"<<"\t2.Bubble Sort <2>\n";
cin>>s;
if(s=1)
mylist.SelectionSort();
else
{
if(s=2)
mylist.BubbleSort();
else
cout<<"error!!\tSelect an Algorithm,use 1 or 2";
}
cout<<"\n\nPrevious sort was:\n";
for(int f=0;f<10;f++)
cout<<n[f]<<"\t";
cout<<"\nCurrent sort is:\n";
for(int x=1;x<11;x++)
cout<<mylist.retrieve(x)<<"\t";
cout<<"\n\n\tWhat you want to do?\n\n\t\t\t1.Sort some new numbers <1>\n\t\t\t2.Exit <2>\n\n\t\t\tEnter 1 or 2:\t";
cin>>a;
if(a==1)
menu();
else
{
if(a=2)
exit(0);
}
}

salman.ba
دوشنبه 04 بهمن 1389, 22:13 عصر
لطفا یکی کمک کنه مشکل این کد چیه؟