-
Notifications
You must be signed in to change notification settings - Fork 1
/
06-insert-sort.js
45 lines (36 loc) · 1.3 KB
/
06-insert-sort.js
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
/*
https://www.codewars.com/kata/linked-lists-insert-sort/javascript
Linked Lists - Insert Sort
Write an InsertSort() function which rearranges nodes in a linked list so they are sorted in
increasing order. You can use the SortedInsert() function that you created in the
"Linked Lists - Sorted Insert" kata below. The InsertSort() function takes the head of a linked list
as an argument and must return the head of the linked list.
var list = 4 -> 3 -> 1 -> 2 -> null
insertSort(list) === 1 -> 2 -> 3 -> 4 -> null
If the passed in head node is null or a single node, return null or the single node, respectively.
You can assume that the head node will always be either null, a single node, or a linked list
consisting of multiple nodes.
The push(), buildOneTwoThree(), and sortedInsert() functions need not be redefined.
*/
const { Node } = require('./00-utils')
const { sortedInsert } = require('./05-sorted-insert')
/*
* The recursion version
*/
function insertSort(head) {
if (!head) return null
return sortedInsert(insertSort(head.next), head.data)
}
/*
* The loop version
*/
function insertSortV2(head) {
for (var sortedList = null, node = head; node; node = node.next) {
sortedList = sortedInsert(sortedList, node.data)
}
return sortedList
}
module.exports = {
insertSort,
insertSortV2,
}