Sie sind auf Seite 1von 5

1|Page

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:

/******************Insertion Sort using LINKED LIST****************/


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#include<process.h>
/***********************************************************/
struct node
{
int info;
struct node *next;
};
/***********************************************************/
typedef struct node N;
/***********************************************************/
N *start, *last, *temp, *prev, *prevx;
/***********************************************************/
void display()
{
if(start==NULL)
{
printf("Underflow. Press any key to continue...");
getch();
return;
}
temp=start;
printf("\nThe elements in the Linked List are:- ");
while(temp!=NULL)
{
printf("\t%d",temp->info);
temp=temp->next;
}
}
/***********************************************************/
void insert()
{
char ch;
3|Page

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

Output of the program in C:

Das könnte Ihnen auch gefallen