Please accomplish these problems in JavaScript with HTML. These problems are to
ID: 3731023 • Letter: P
Question
Please accomplish these problems in JavaScript with HTML. These problems are to refresh your memory with array, functions and sorting a little bit. I have provided the hints accordingly.
Problem-1
Let A and B two arrays of n elements, each. Given a number K, give an O(nlogn) time algorithm for determining whether there exists a A and b B suck that a + b = K.
Hints:
1. Use Heapsort(A, n) or Quicksort(A)
2. Take Advantage of BinarySearch()
make sure write a program in the HTML and Javascript not in C language
Explanation / Answer
Program Heapsort
<html>
<head>
<title> Heap Sort </title>
</head>
<body>
<script>
var values=[];
document.write("<br><br>");
for (a=0; a<10; a++)
{
values.push(Number(prompt("Enter item value at no. " + (a+1))));
}
document.write(" User Enter");
document.write("<br><br>");
for (a=0;a<10; a++)
{
document.write(" "+values[a]+" ");
}
function swap(data, i, j)
{
var tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
function heap_sort(arr)
{
fun1(arr);
end = arr.length - 1;
while(end > 0) {
swap(arr, 0, end);
fun2(arr, 0, end);
end -= 1
}
}
function fun1(arr)
{
var i;
i = arr.length / 2 - 1;
i = Math.floor(i);
while (i >= 0) {
fun2(arr, i, arr.length);
i -= 1;
}
}
function fun2(heap, i, max)
{
var i_big, c1, c2;
while(i < max)
{
i_big = i;
c1 = 2*i + 1;
c2 = c1 + 1;
if (c1 < max && heap[c1] > heap[i_big])
i_big = c1;
if (c2 < max && heap[c2] > heap[i_big])
i_big = c2;
if (i_big == i) return;
swap(heap,i, i_big);
i = i_big;
}
}
heap_sort(values);
document.write("<br><br>");
document.write("Sorted Numbers");
document.write("<br><br>");
for (a=0; a<10; a++)
{
document.write(" " + values[a]+ " ");
}
</script>
</body>
</html>
OUTPUT
User Enter
5 8 2 9 3 5 9 1 6 4
Sorted Numbers
1 2 3 4 5 5 6 8 9 9
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.