Reputation: 1
I'm trying to display the sorted array using javascript DOM but it is only displaying the entered array.what did i do wrong?
for eg for array Arr[7,8,2,3,5,4] when i ran the js file seperate without Dom it displayed [2,3,4,5,7,8] but when using DOM [7,8,2,3,5,4]
function BubbleSort(Arr){
var temp;
var Arr=document.getElementById("data1").value;
for(let i=0;i<Arr.length-1;i++){
for(let j=0;j<Arr.length-i-1;j++){
if(Arr[j] > Arr[j+1]){
temp = Arr[j];
Arr[j] = Arr[j+1];
Arr[j+1] = temp;
}
}
}
console.log(Arr);
document.getElementById("demo").innerHTML="the answer is :" +Arr;
};
Upvotes: 0
Views: 76
Reputation: 3229
The problem is you're reading something from the DOM and passing it in as an array. After you read in the value from "data1" make sure it's an array before passing it to your function.
function BubbleSort() {
var temp;
var Arr = document.getElementById("data1").value;
// this next line will split the input if you're setting it as a string
Arr = Arr.split(',');
for (let i = 0; i < Arr.length - 1; i++) {
for (let j = 0; j < Arr.length - i - 1; j++) {
if (Arr[j] > Arr[j + 1]) {
temp = Arr[j];
Arr[j] = Arr[j + 1];
Arr[j + 1] = temp;
}
}
}
console.log(Arr);
document.getElementById("demo").innerHTML = "the answer is :" + Arr;
}
BubbleSort();
<input type="text" id="data1"></input>
<div id="demo"></div>
<button onclick="BubbleSort()">Sort</button>
Upvotes: 1
Reputation: 11
So, you're providing Arr as an argument, but then you're ignoring it and redeclaring Arr
var Arr=document.getElementById("data1").value;
Comment that line out and it should work fine.
Upvotes: 0