@seungha/

mergeSortAndSelectionSort

ES6

No description

fork
loading

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.7034390326370736","path":"main.js","file":{"path":"main.js","content":{"asEncoding":{"base64":"ZnVuY3Rpb24gbWVyZ2VTb3J0KGFycikgewogIGlmIChhcnIubGVuZ3RoIDw9IDEpIHJldHVybiBhcnI7CiAgY29uc3Qgc2xpY2VyID0gTWF0aC5mbG9vcihhcnIubGVuZ3RoIC8gMik7CiAgY29uc3QgYXJyMSA9IG1lcmdlU29ydChhcnIuc2xpY2UoMCwgc2xpY2VyKSk7CiAgY29uc3QgYXJyMiA9IG1lcmdlU29ydChhcnIuc2xpY2Uoc2xpY2VyKSk7CiAgY29uc3QgbmV3QXJyID0gW107CiAgZm9yIChsZXQgaSA9IDAsIGogPSAwOyBpIDwgYXJyMS5sZW5ndGggfHwgaiA8IGFycjIubGVuZ3RoOyApIHsKICAgIGlmIChhcnIxW2ldID09IHVuZGVmaW5lZCB8fCBhcnIxW2ldID4gYXJyMltqXSkgewogICAgICBuZXdBcnIucHVzaChhcnIyW2pdKTsKICAgICAgaisrOwogICAgfSBlbHNlIHsKICAgICAgbmV3QXJyLnB1c2goYXJyMVtpXSk7CiAgICAgIGkrKzsKICAgIH0KICB9CiAgcmV0dXJuIG5ld0FycjsKfQoKZnVuY3Rpb24gc2VsZWN0aW9uU29ydChhcnIpIHsKICBmb3IgKGxldCBpID0gMDsgaSA8IGFyci5sZW5ndGg7IGkrKykgewogICAgbGV0IG1pbkluZGV4ID0gaTsKICAgIGZvciAobGV0IGogPSBpICsgMTsgaiA8IGFyci5sZW5ndGg7IGorKykgewogICAgICBpZiAoYXJyW2pdIDwgYXJyW21pbkluZGV4XSkgewogICAgICAgIG1pbkluZGV4ID0gajsKICAgICAgfQogICAgfQogICAgW2FycltpXSwgYXJyW21pbkluZGV4XV0gPSBbYXJyW21pbkluZGV4XSwgYXJyW2ldXTsKICB9CiAgcmV0dXJuIGFycjsKfQoKY29uc3QgYXJyID0gbmV3IEFycmF5KDUwMDAwKS5maWxsKG51bGwpLm1hcChNYXRoLnJhbmRvbSk7Cgpjb25zb2xlLnRpbWUoJ21lcmdlU29ydCcpOwptZXJnZVNvcnQoYXJyKTsKY29uc29sZS50aW1lRW5kKCdtZXJnZVNvcnQnKTsKCmNvbnNvbGUudGltZSgnc2VsZWN0aW9uU29ydCcpOwpzZWxlY3Rpb25Tb3J0KGFycik7CmNvbnNvbGUudGltZUVuZCgnc2VsZWN0aW9uU29ydCcpOw=="},"asBuffer":null},"loaded":true}}
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
function mergeSort(arr) {
  if (arr.length <= 1) return arr;
  const slicer = Math.floor(arr.length / 2);
  const arr1 = mergeSort(arr.slice(0, slicer));
  const arr2 = mergeSort(arr.slice(slicer));
  const newArr = [];
  for (let i = 0, j = 0; i < arr1.length || j < arr2.length; ) {
    if (arr1[i] == undefined || arr1[i] > arr2[j]) {
      newArr.push(arr2[j]);
      j++;
    } else {
      newArr.push(arr1[i]);
      i++;
    }
  }
  return newArr;
}

function selectionSort(arr) {
  for (let i = 0; i < arr.length; i++) {
    let minIndex = i;
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[j] < arr[minIndex]) {
        minIndex = j;
      }
    }
    [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]];
  }
  return arr;
}

const arr = new Array(50000).fill(null).map(Math.random);

console.time('mergeSort');
mergeSort(arr);
console.timeEnd('mergeSort');

console.time('selectionSort');
selectionSort(arr);
console.timeEnd('selectionSort');
Babel Compiler v6.4.4 Copyright (c) 2014-2015 Sebastian McKenzie