-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedListInsertionSort.c
More file actions
62 lines (55 loc) · 1.29 KB
/
linkedListInsertionSort.c
File metadata and controls
62 lines (55 loc) · 1.29 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
//
// Created by ali raz on 6/4/20.
//
#include <stdlib.h>
#include <stdio.h>
#include "linkedListInsertionSort.h"
//C Program for Bubble Sort on Linked List
typedef struct node {
struct node *next;
int val;
} node;
void sortNode(node **start, int value) {
node *previous = NULL;
node *curr = *start;
while (curr != NULL) {
if (curr->val < value) {
previous = curr;
curr = curr->next;
} else {
node *new;
new = malloc(sizeof(struct node));
if (previous == NULL) {
*start =new;
} else {
previous->next = new;
}
new->val = value;
new->next = curr;
return;
}
}
curr = malloc(sizeof(node));
previous->next = curr;
curr->next = NULL;
curr->val = value;
}
void insertionSortUsingLinkedLists(int arr[], int length) {
node *start;
start = malloc(sizeof(node));
start->next = NULL;
start->val = arr[0];
for (int i = 1; i < length; ++i) {
sortNode(&start, arr[i]);
}
int i = 0;
node *curr = start;
node *previous;
while (curr != NULL) {
arr[i] = curr->val;
i++;
previous=curr;
curr = curr->next;
free(previous);
}
}