-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselectionSort.c
More file actions
123 lines (104 loc) · 2.11 KB
/
selectionSort.c
File metadata and controls
123 lines (104 loc) · 2.11 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
/* pseudocode: */
/*
Function selectionSort(Type data[1..n])
Index i, j, max
For i from 1 to n do
max = i
For j from i + 1 to n do
If data[j] > data[max] then
max = j
Exchange data[i] and data[max]
End
*/
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct Node{
int value;
struct Node *next;
};
struct Node *head = NULL;
struct Node *swap(struct Node*, struct Node *);
// this code still have errors.
void selectionSort(struct Node *head){
struct Node *prev = NULL;
struct Node *current = NULL;
struct Node *check = NULL;
struct Node *max = NULL;
struct Node *newhead = NULL;
int maxmum = -1;
bool change = false;
current = head;
while(current->next != NULL){
maxmum = current->value;
check = current->next;
change = false;
while(check != NULL){
if(check->value > maxmum){
maxmum = check->value;
max = check;
change = true;
}
check = check->next;
}
if(change){
current = swap(current, max);
if(prev != NULL)
prev->next = current;
else
newhead = current;
// if(newhead == NULL){
// }
}
prev = current;
current = current->next;
printf("value is %d\n",maxmum);
}
printf("After sorting : \n");
while(newhead != NULL){
printf("value is %d\n", newhead->value);
newhead = newhead->next;
}
}
struct Node *swap(struct Node *p, struct Node *q){
struct Node *temp = q->next;
q->next = p;
p->next = temp;
return q;
}
void push_value(int value){
struct Node *current = head;
while(current->next != NULL){
current = current->next;
}
struct Node *newnode = malloc(sizeof(struct Node));
newnode->value = value;
newnode->next = NULL;
current->next = newnode;
}
int main(void)
{
head = malloc(sizeof(struct Node));
head->value = 1;
push_value(3);
push_value(2);
push_value(7);
push_value(8);
push_value(4);
push_value(9);
/*
push_value(2);
push_value(7);
push_value(8);
push_value(3);
push_value(6);
push_value(2);
push_value(1);
push_value(1);
push_value(8);
*/
printf("Before Sorting : 1, 3, 2\n");
// printf("Before Sorting : 3, 2, 7, 8, 3, 6, 2, 1, 1, 8\n");
selectionSort(head);
return 0;
}