Professional Documents
Culture Documents
Insertion Sort: Q. To Perform Insertion Sorting Using Singly Linked List, Where The Linked List (1) Might Be Empty
Insertion Sort: Q. To Perform Insertion Sorting Using Singly Linked List, Where The Linked List (1) Might Be Empty
INSERTION SORT
Q. To perform Insertion Sorting using singly linked list, where the linked list (1) might be empty, (2)
might have a single node (3) might have more than one nodes.
Ans.
Algorithm:
Function insert
begin
P←getnode()
if (start=∆) then
begin
start←P
last←P
link(start)←∆
link(last)←∆
end
else if(info(start)>=info(P)) then
begin
link(P)←start
start←P
end
else if(info(last)<=info(P)) then
begin
link(last)←P
last←P
link(last)←∆
end
else
begin
prevx←start
prev←link(start)
repeat until (link(prevx)!=∆)
begin
if(info(prev)>=info(P)) then
begin
link(P)←prev
link(prevx)←P
2|Page
break
end
prev←link(prev)
prevx←link(prevx)
end
end
end
Program in language C:
do
{
temp=(N*)malloc(sizeof(N));
printf("\n\nEnter the number: ");
scanf("%d",&temp->info);
if(start==NULL)
{
start=temp;
last=temp;
start->next=NULL;
last->next=NULL;
}
else if(start->info>=temp->info)
{
temp->next=start;
start=temp;
}
else if(last->info<=temp->info)
{
last->next=temp;
last=temp;
last->next=NULL;
}
else
{
prevx=start;
prev=start->next;
while(prevx->next!=NULL)
{
if(prev->info>=temp->info)
{
temp->next=prev;
prevx->next=temp;
break;
}
prev=prev->next;
prevx=prevx->next;
}
}
display();
printf("\n\nPress [Y] to insert again: ");
ch=getche();
}while(ch=='y'||ch=='Y');
}
/***********************************************************/
void main()
{
int ch;
clrscr();
4|Page
printf("\n\n\t\t\t\tINSERTION SORT");
back:
printf("\n\tMENU\n");
printf("\n\t\t0> Exit.");
printf("\n\t\t1> Insert.");
printf("\n\t\t2> Display.\n\t");
printf("Choice: ");
scanf("%d",&ch);
if(ch==1)
insert();
if(ch==2)
display();
if(ch==0)
exit(0);
goto back;
}
/***********************************************************/
5|Page