I started a challenge to some javascript folks last month, and here is the write-up.

Challenge

I gave them this array [5,23,87,3,58,7,2,1,9], and asked them to sort it increasingly.

It’s really easy task to do, so I made some rules to make it harder.

Rules :

  • Use only one integer varialbe.
  • Use only one loop.
  • Use only one built-in fucntion to do the sorting (output function was not counted).
  • Short and fatest code will get a cookie.



Solutions

So I got some good submissions, and here it is :

Fareed’s first submission was :

document.write("1,2,3,5,7,9,23,58,87");

He said it is outside the box :D I told him to get back to the box.

His second submission was ideal:

data = [5,23,87,3,58,7,2,1,9];
var i = 0;
while(true)
{
    if (data[i % (data.length-1)] > data[i % (data.length-1) +1])
    {
    	data[i % (data.length-1)] += data[i % (data.length-1)+1];
        data[i % (data.length-1)+1] = data[i % (data.length-1)]-data[i % (data.length-1)+1];
        data[i % (data.length-1)] -= data[i % (data.length-1)+1];
    }
    
    if (i>(data.length)*(data.length))
    {break;}
    i += 1;
}
console.log(data);

One loop, one variable, one function. Totally acceptable. In my opionion he should write a write-up about his solution.


Shweelan’s solution :

var data = [5,23,87,3,58,7,2,1,9];
function calc () {
for (var i = 0; i < data.length - 1; i++) {
if (data[i] < data[data.length - 1]) {
// swap
data[data.length - 1] = data[data.length - 1] ^ data[i];
data[i] = data[data.length - 1] ^ data[i];
data[data.length - 1] = data[data.length - 1] ^ data[i];
}
}
console.log(data[data.length - 1]);
data.length -= 1;
if (data.length) {
calc();
}
}
calc();

This solution was an amazing approach, with amazing swap technique.

The model solution :

I used the sleep sortiong algorithm. It is a method to sort elements using sleep function:

function mymethod(){
var data = [5,23,87,3,58,7,2,1,9];
data.forEach(number =>{
setTimeout(() => {console.log(number)}, number );
});
}


Sleep sort algorithm

It is a joke more than an algorithm, but it is really fast in sorting numbers less than 1000 and geater than 0 (in JS).
The disadvantages of this algorithm :

  • Does not work for negative numbers since you can not wait to negative per of time .
  • Big numbers can took forever to get sorted , e.g (4,100000000,1,25990021,100300330) .
  • Sometimes it gives a wrong output .