-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertionSort.js
More file actions
50 lines (37 loc) · 1.71 KB
/
insertionSort.js
File metadata and controls
50 lines (37 loc) · 1.71 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
// Insertion sort is a basic sorting algorithm.
// Insertion sort iterates over an array, growing a sorted array behind the
// current location. It takes each element from the input and finds the spot,
// up to the current point, where that element belongs (in constant space).
// It does this until it gets to the end of the array.
// Insertion sort should be implemented as a stable sort. This means that
// equal elements should retain their relative order. Numbers, as primitives,
// give us no way to check this, so we’ll be sorting objects with a value field,
// on which they will be sorted, like so:
// [{value: 10}, {value: 5, order: 1}, {value: 5, order: 2}]
// [{value: 5, order: 1}, {value: 5, order: 2}, {value: 10}]
// EXTRA CREDIT:
// Refactor your sort to (optionally) take an explicit comparator function
// as its second argument, so that callers can define arbitrary ways to sort
// elements. See Array.prototype.sort for an example of how this works
// (excerpt below):
// If comparator(a, b) is less than 0, sort a to a lower index
// than b, i.e. a comes first.
// If comparator(a, b) returns 0, leave a and b unchanged with respect to each
// other, but sorted with respect to all different elements.
// If comparator(a, b) is greater than 0, sort b to a lower index than a.
// If no comparator is given, just sort the elements using < or >
function insertionSort (arrObj) {
var arr = [];
var result = [];
for(var i = 0; i < arrObj.length; i++){
if(arrObj[i].hasOwnProperty("order")){
}
arr.push(arrObj[i]["value"])
}
// arr = arr.sort();
console.log(arr.sort(function(a, b){return a - b}));
for(var i = 0; i < arr.length; i++){
result.push({value: arr[i]})
}
return result;
}