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

Coding for Kids

What is coding? In coding we build a program to do a specific task for us. Code: A code is a set of computer instructions and when you will ...