forked from till-tomorrow/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Insertion Sort
84 lines (70 loc) · 1.44 KB
/
Insertion Sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <iostream>
using namespace std;
// A structure to represent a node.
struct list
{
int data;
list *next;
};
// Function implementing insertion sort.
list* InsertinList(list *head, int n)
{
// Creating newnode and temp node.
list *newnode = new list;
list *temp = new list;
// Using newnode as the node to be inserted in the list.
newnode->data = n;
newnode->next = NULL;
// If head is null then assign new node to head.
if(head == NULL)
{
head = newnode;
return head;
}
else
{
temp = head;
// If newnode->data is lesser than head->data, then insert newnode before head.
if(newnode->data < head->data)
{
newnode->next = head;
head = newnode;
return head;
}
// Traverse the list till we get value more than newnode->data.
while(temp->next != NULL)
{
if(newnode->data < (temp->next)->data)
break;
temp=temp->next;
}
// Insert newnode after temp.
newnode->next = temp->next;
temp->next = newnode;
return head;
}
}
int main()
{
int n, i, num;
// Declaring head of the linked list.
list *head = new list;
head = NULL;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>num;
// Inserting num in the list.
head = InsertinList(head, num);
}
// Display the sorted data.
cout<<"\nSorted Data ";
while(head != NULL)
{
cout<<"->"<<head->data;
head = head->next;
}
return 0;
}