H
H
hydra_132019-11-04 13:48:22
JavaScript
hydra_13, 2019-11-04 13:48:22

What is sorting (JS)?

Greetings!
I tried to make a quick sort (quick sort) without really understanding its theory, I realized that I used not quite the right approach. Here is the code:

const inputArray = [7, 4, 2, 8, 6, 1, 0, 9, 5, 3];

//my version
function sort(arr) {
  if (arr.length < 2) {
    return arr;
  }
  const baseElIndex = Math.floor(arr.length / 2);
  const baseElValue = arr[baseElIndex];
  const arrMin = [];
  const arrSame = [];
  const arrMax = [];
  arr.forEach(item => {
    if (item == baseElValue) {
      arrSame.push(item);
    } else if (item < baseElValue) {
      arrMin.push(item);
    } else if (item > baseElValue) {
      arrMax.push(item);
    }
  });
  return sort(arrMin)
    .concat(arrSame)
    .concat(sort(arrMax));
}

console.log(sort(inputArray));

Conclusion:
> node .\sort.js
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

Question: what kind of sorting was implemented in my case?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
longclaps, 2019-11-04
@longclaps

not really understanding her theory
It sounds funny.
Yes, this is quick sort in its toy version, and even a little worse (there is redundant checking).
The non-toy version is more memory-efficient, but requires careful work with indexes.

A
Arthur Mustafin, 2019-11-04
@virtual_hack2root

This is Merge Sort
Python Example
https://studlearn.com/works/details/sortirovka-sli...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question