1

Here is the link to my JavaScript Insertion Sort Algorithm

Quite simply, I just can't figure out why I can't get that pesky arr[0] to get sorted correctly. I've tried everything I know of. sigh

It's pretty close though.

Any idea's

var aoo = [5,2,4,6,1,3];

function jInsertionSort(a) {
  for(var j=2; j<a.length; j++){
    //console.log(j);
    var key = a[j]; 
    var i = j - 1;
    while (i > 0 && a[i] > key) {
      a[i+1] = a[i]; 
      i = i-1; 
    }
    a[i+1]=key; 
  } 
  return a; 
}

var aooSorted = jInsertionSort(aoo);

console.log("jInsertionSort = ["+aooSorted+"]");

?

JavaScript Insertion Sort Algorithm

2 Answers 2

2

You almost got it, this works:

var aoo = [5,2,4,6,1,3];

function jInsertionSort(a) {
    for(var j=1; j<a.length; j++){
        var key = a[j]; 
        var i = j;
        while (i > 0 && a[i-1] > key) {
            a[i] = a[i - 1];
            a[i - 1] = key;
            i = i-1; 
        }
    } 
    return a; 
}

var aooSorted = jInsertionSort(aoo);

console.log("jInsertionSort = ["+aooSorted+"]");

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

1 Comment

I upvoted your answer since it's shorter than mine and works well. I cannot speak for OP and I highly doubt he took his time to check I was from Mexico. Just chill I didn't even get that many points
0

var aoo = [5,2,4,6,1,3];

function jInsertionSort (a) {
  for (var i = 0; i < a.length; i++) {
    var k = a[i];
    for (var j = i; j > 0 && k < a[j - 1]; j--)
        a[j] = a[j - 1];
    a[j] = k;
  }
  return a;
}

var aooSorted = jInsertionSort(aoo);

console.log("jInsertionSort = ["+aooSorted+"]");

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.