0

i'm trying to construct a code that uses the selection-sort method, but i'm having trouble. When i press my button nothing happens. I figure having a second pair of eyes on the code would help me find out what's wrong.

Is my swap() function correct? Is my select() function correct? What am I doing wrong? All help is welcome!

<input id="input1" type="number" min="5" max="1000" onchange="first(); sortButton();">

<p id="demo"></p>

<!-- button appears here, once a value is entered into the input field -->
<p id="buttons1" onclick="select();"></p>


<p id="demo2"></p>

<script>


// once input1 value changes this outputs a random value less than N (value of input1) N times, then dumps out the random numbers in id="demo"

var arr = [];
function first() {
var N = document.getElementById("input1").value;
while(arr.length < N)

{var randomnumber = Math.ceil(Math.random()*N);
arr[arr.length] = randomnumber;}
document.getElementById("demo").innerHTML = arr;}


// Once input1 value changes, this buttons appears in id="buttons"
function sortButton() {document.getElementById("buttons1").innerHTML =
'<button type="button" onclick="select();">Select Sort</button>';}


function swap(arr, i, min) {
var temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;}


// meant to sort (selection sort method) the random numbers in id="demo" once the button is clicked

function select() {var len = arr.length, min, i,  j;
for (i = 0; i < len; i++){min = i; for (j = i+1; j < len; j++){if (arr[j] < arr[min]){min = j;}} if (i != min){swap(arr, i, min);} } return arr;}




</script>
7
  • Inner Html is expected to be a string. Convert arr to string using arr.join("") Commented Nov 13, 2016 at 18:51
  • where would i write that? -- bare with me i'm very new to js lol Commented Nov 13, 2016 at 18:53
  • Blablabla.innerHTML=arr.join(""); Commented Nov 13, 2016 at 18:55
  • document.getElementById("demo2").innerHTML = arr.join("");} correct? Commented Nov 13, 2016 at 18:57
  • Yep. That was point one. Commented Nov 13, 2016 at 18:58

1 Answer 1

2

Your select function is a mess. Theres a standard function called sort, that does that for you:

function select(){
arr.sort(function(a,b){
 //if a<b keep it, if not swap
 if(a<b){
   return 0;
 }else{
   return 1;
 }
 });

https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

You can even short it:

function select(){
 arr.sort((a,b)=>a-b);
 }

(See arrow functions for more info)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.