编写一个算法,在基于单链表表示的待排序关键字序列上进行简单选择排序
#include <iostream>
#include <time.h>
#include <stdlib.h>
typedef struct node{int data;struct node *next;
}node,*pnode;pnode buynode(int x)
{pnode tmp=(pnode) malloc(sizeof (node));tmp->data=x,tmp->next= nullptr;return tmp;
}pnode buidlink()
{pnode head= buynode(-1);pnode tmp=head;for(int i=0;i<10;i++) tmp=tmp->next= buynode(rand()%20);return head;
}
void print(pnode head)
{while(head->next){printf("%3d",head->next->data);head=head->next;}puts("");
}void swap(pnode &n1,pnode &n2)
{int tmp=n1->data;n1->data=n2->data;n2->data=tmp;
}
void sort(pnode head)
{while(head->next){pnode tmp=head->next;pnode record=tmp;while(tmp->next){if(record->data>tmp->next->data)record=tmp->next;tmp=tmp->next;}if(tmp!=head->next) swap(head->next,record);head=head->next;}
}
int main() {srand(time(nullptr));pnode h1=buidlink();print(h1);sort(h1);print(h1);return 0;
}