/
Linked_List_Selection_Sort.cpp
94 lines (83 loc) · 1.25 KB
/
Linked_List_Selection_Sort.cpp
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
85
86
87
88
89
90
91
92
93
94
#include <bits/stdc++.h>
using namespace std;
struct node
{
int value;
node* next;
};
node *first, *temp;
void insert(int val);
void display();
void selectionSort();
void insert(int val)
{
if (first == NULL)
{
first = new node();
first -> value = val;
first -> next = NULL;
}
else
{
temp = first;
while (temp -> next)
{
temp = temp -> next;
}
temp -> next = new node();
temp = temp -> next;
temp -> value = val;
temp -> next = NULL;
}
}
void display()
{
temp = first;
while (temp)
{
cout << temp -> value << " ";
temp = temp -> next;
}
cout << "\n";
}
void selectionSort()
{
node *beg = first;
node *minimum = first;
while (beg -> next != NULL)
{
minimum = beg;
node *current = beg -> next;
while (current)
{
if (current -> value < minimum -> value)
{
minimum = current;
}
current = current -> next;
}
int t = beg -> value;
beg -> value = minimum -> value;
minimum -> value = t;
beg = beg -> next;
}
}
int main()
{
insert(1);
insert(8);
insert(5);
insert(4);
insert(9);
insert(2);
cout << "Before sorting : ";
display();
selectionSort();
cout << "After Sorting : ";
display();
return 0;
}
/*Output:
Before sorting: 1 8 5 4 9 2
After sorting: 1 2 4 5 8 9
*/