简体   繁体   English

插入排序不适用于JavaScript

[英]Insertion sort doesn't work in JavaScript

I don't know why my script doesn't work it returns the same length as my input but the algorythm, seem to don't work. 我不知道为什么我的脚本不起作用,它返回的长度与我输入的长度相同,但是算法似乎不起作用。

 var n = prompt("Entrer la taille de votre tableau:"); a = new Array(); b = new Array(); a.length = n; b.length = n; var i = 0, j = 0; for (i = 0; i < n; i++) { a[i] = prompt("Entrer les valeurs de votre tableau:"); }; console.log(a); // Algorithm part : for (i = 0; i < n; i++) { b[j] = a[i]; for (j = i; j > 0 && a[j - 1] > b[i]; j--) { a[j] = a[j - 1]; } a[j] = b[i]; } console.log(b); console.log(b.length); 

I'm not really sure how you envisioned that code working. 我不确定您如何设想该代码如何工作。 You're using i in places where you should be using j and assigning values back and forth between arrays a and b in a way that doesn't make sense to me. 您在应该使用j地方使用i ,并且以对我来说没有意义的方式在数组ab之间来回分配值。

The way to make this work is to only work within the b array, and just copy values in from a one at a time. 使这项工作的方式是将内唯一的工作b阵列,只是从值复制a一次一个。 In the inner loop, j should be initialized to the value of i , but i shouldn't be used in that loop after that. 在内部循环中,应将j初始化为i的值,但此后不应该在该循环中使用i

One more problem was that you weren't converting the inputs to numbers, so all of the comparisons were being made as string comparisons. 另一个问题是您没有将输入转换为数字,因此所有比较都作为字符串比较进行。

The following should work: 以下应该工作:

 var n = prompt("Entrer la taille de votre tableau:"); a = new Array(); b = new Array(); a.length = n; b.length = n; var i = 0; var j = 0; var temp; for (i = 0; i < n; i++) { a[i] = Number(prompt("Entrer les valeurs de votre tableau:")); }; console.log(a); // Algorithm part : for (i = 0; i < n; i++) { // Place the ith value of a in b b[i] = a[i]; // Move backwards from i, swapping values until the inserted value is in the correct place for (j = i; j > 0 && b[j - 1] > b[j]; j--) { // swap temp = b[j]; b[j] = b[j - 1]; b[j - 1] = temp; } } console.log(b); console.log(b.length); 

j is not defined at the start of the loop, so the line 'b[j]=a[i]' does not do what you might expect. j在循环开始时未定义,因此行'b [j] = a [i]'并没有达到您的期望。 You are also sorting in a not in b . 您还在a不按b排序。 I don't think that is what you intended so the following code sorts in b. 我认为这不是您想要的,因此以下代码在b中排序。

//define some values
const a=[3,6,8,4,5,2,7,1];
const n=a.length;
const b=new Array(n);

//now do the insertion sort
for (let i = 0; i < n; i++) {
  let j;
  for (j = i; j > 0 && b[j - 1] > a[i]; j--) {
    b[j] = b[j - 1];
  }
  b[j] = a[i];
}

console.log(b);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM