1. Use the merge function to write a sorting algorithm. This has to be in HTML f
ID: 3809176 • Letter: 1
Question
1. Use the merge function to write a sorting algorithm. This has to be in HTML format with some javascript in it The algorithm is as follows:
function newsort(array):
if array length <= 1:
// an array of length 1 is already sorted
return array
else:
// divide the array in half, sort them separately
// and then merge them back together
mid = middle index of array
left = a new array of size mid
right = a new array of size array length – mid
copy leftmost elements of array into left
copy rightmost elements of array into right
left = newsort(left)
right = newsort(right)
result = merge(left, right);
return result
2. Verify that the sorting algorithm above actually sorts some data. Then profile the new sorting algorithm and compare it against the other sorting algorithms you have studied. Produce a plot similar to that given in the key points that shows the relationship between the time it takes to sort and the number of elements in the array. The following functions should help you with this problem:
// build an array of random data to sort
function makeRandomArray(size)
{
var result = Array();
while (size > 0)
{
result.push(Math.floor(Math.random()*100000));
--size;
}
return result;
}
// time the sorting algorithm on the given array, in milliseconds
function timeSortingAlgorithm(arr, sortingAlgorithm)
{
var startTime = new Date()
sortingAlgorithm(arr);
var endTime = new Date();
return endTime.getTime() - startTime.getTime();
}
Explanation / Answer
merge function to write a sorting algorithm ....code in javascript.
var a = [34, 203, 3, 746, 200, 984, 198, 764, 9];
function newsort(array)
{
if (array.length < 1){
return array;
}
else{
var middle = parseInt(array.length / 2);
var left = array.slice(0, middle);
var right = array.slice(middle, array.length);
return merge(mergeSort(left), mergeSort(right));
while (left.length && right.length) {
if (left[0] <= right[0]) {
array.push(left.shift());
} else {
array.push(right.shift());
}
}
while (left.length)
array.push(left.shift());
while (right.length)
array.push(right.shift());
return array;
}
}
put this in html <script> ... </script>. of your program where you have to use
hope it will help you ...
thanks
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.