Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In Javascript SortMyArray Write a function that takes in an array of integers an

ID: 3701972 • Letter: I

Question

In Javascript

SortMyArray

Write a function that takes in an array of integers and sorts the array from smallest to largest. Your function should return an array with the sorted list and print the list out. You can assume that the array being passed will always have integers (You do not need to type check the array). DO NOT USE the built-in array sort function.

These are sample input and output that should be displayed:

var arr1=[-3,8,7,6,5,-4,3,2,1];

console.log(SortMyArray(arr1));

[ -4, -3, 1, 2, 3, 5, 6, 7, 8 ]

var test_array=[1,2,3,4,5];

console.log(SortMyArray(test_array));

[ 1,2,3,4,5]

var test_array=[];

console.log(SortMyArray(test_array));

Cannot sort an Empty Array!

var test_array=[1,-1,-2,2,3,-3,-4,4,5,-5,0];

console.log(SortMyArray(test_array));

[ -5,-4,-3,-2,-1,0,1,2,3,4,5]

var test_array=[1, 1, 1, 100, 75, 2, 2, 37, 55, 55];

console.log(SortMyArray(test_array));

[1,1,1,2,2,37,55,55,75,100]

Explanation / Answer

Please find my implementation:

Please let me know in case of any issue.

<html>
<head>
<script type="text/javascript">
var arr = [-3,8,7,6,5,-4,3,2,1];
//taking size of array

if(arr.length<1)
{
alert("array cant be empty");
}

//it will print on console
console.log(SortMyArray(arr));

//sort function
function SortMyArray(arr)
{
for(var i =0;i<arr.length;i++)
{
for(var j= 0;j<(arr.length-i-1);j++)
{
if(arr[j]>arr[j+1])
{
var swap = arr[j];
arr[j] = arr[j+1];
arr[j+1] = swap;
}
}
}
return arr;//return sorted array
}


</script>

<title>SortMyArray</title>

</html>

Please DONT forgot to rate my answer, we are working hard for you guys!!

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote