Implement the selection sort algorithm on the memory that should be able to hold five hundred elements and these elements should be of node type?
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
struct node{
int number;
node *next;
};
void memory(void);
void adding(void);
void sorting(void);
node *tmp,*head,*curr,*pre;
void memory(){
head = new node;
curr=head;
curr->next = NULL;
for(int i=1;i<500;i++){
curr->next = new node;
pre = curr;
curr = curr->next;
}
curr->next=NULL;
}
void adding(){
int len=50;
while(len>=1){
len--;
curr->number = len*rand()%100+7;
curr = curr->next;
}
curr = head;
}
void sorting(){
int len=0;
while(curr->number!=0){
len++;
curr = curr->next;
}
node *point[len];
tmp=head;
for(int i=0;i<len && tmp!=NULL;i++) {
point[i]=tmp; tmp=tmp->next;
}
int i,j,low,lowat;
for(i=0;i<(len-1);i++)
{
lowat=i;
low=point[i]->number;
for(j=i+1;j<(len);j++) //select the lowest number of the rest of array
{
if(low>point[j]->number) //ascending order for descending reverse
{
lowat=j; //the position of the low element
low=point[j]->number;
}
}
int temp=point[i]->number ;
point[i]->number=point[lowat]->number; //swap
point[lowat]->number=temp;
}
int main(){
memory();
adding();
tmp = head;
cout <<"Data set before sorting : \n";
while(tmp->number!=NULL){
if(tmp!=NULL){cout << tmp->number<<"\t";
tmp = tmp->next;}
}
cout<<"\n\n";
sorting();
tmp = head;
cout <<"Data set after sorting : \n";
while(tmp->number!=NULL){
if(tmp!=NULL){cout << tmp->number<<"\t";
tmp = tmp->next;}
}
cout <<endl;
system("pause");
}
}
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
struct node{
int number;
node *next;
};
void memory(void);
void adding(void);
void sorting(void);
node *tmp,*head,*curr,*pre;
void memory(){
head = new node;
curr=head;
curr->next = NULL;
for(int i=1;i<500;i++){
curr->next = new node;
pre = curr;
curr = curr->next;
}
curr->next=NULL;
}
void adding(){
int len=50;
while(len>=1){
len--;
curr->number = len*rand()%100+7;
curr = curr->next;
}
curr = head;
}
void sorting(){
int len=0;
while(curr->number!=0){
len++;
curr = curr->next;
}
node *point[len];
tmp=head;
for(int i=0;i<len && tmp!=NULL;i++) {
point[i]=tmp; tmp=tmp->next;
}
int i,j,low,lowat;
for(i=0;i<(len-1);i++)
{
lowat=i;
low=point[i]->number;
for(j=i+1;j<(len);j++) //select the lowest number of the rest of array
{
if(low>point[j]->number) //ascending order for descending reverse
{
lowat=j; //the position of the low element
low=point[j]->number;
}
}
int temp=point[i]->number ;
point[i]->number=point[lowat]->number; //swap
point[lowat]->number=temp;
}
int main(){
memory();
adding();
tmp = head;
cout <<"Data set before sorting : \n";
while(tmp->number!=NULL){
if(tmp!=NULL){cout << tmp->number<<"\t";
tmp = tmp->next;}
}
cout<<"\n\n";
sorting();
tmp = head;
cout <<"Data set after sorting : \n";
while(tmp->number!=NULL){
if(tmp!=NULL){cout << tmp->number<<"\t";
tmp = tmp->next;}
}
cout <<endl;
system("pause");
}
}
No comments:
Post a Comment