JavaScript method to sort an array

Took 5 minutes and 2 seconds to code JavaScript method to return a sorted array. Here is the code snippet.

Code:

arr = [3, 5, 2, 4];
function sort(arr) {
for (var i = 0; i < arr.length; i++) {
for (var y = i + 1; y < arr.length; y++) {
if (arr[i] > arr[y]) {
k = arr[i];
arr[i] = arr[y];
arr[y] = k;
}
}
}
return arr;
}

document.write(sort(arr));

Result:

2,3,4,5

No comments:

Post a Comment

GITEX Dubai Talk by Saion Gupta and Saiasmi Gupta

Good morning, everyone. I'm Saion Gupta, the Founder of 10xCoderKids and the Guinness World Record holder for the youngest computer prog...