2014-12-08 2 views
0

요소 배열 [5,4,3]을 전달합니다. 버블 정렬은 5를 끝까지 처리하지만 괜찮습니다.하지만 마지막 요소를 찾기 위해 세 번째로 반복 할 때 루프가 끊어지며 잘못된 정렬 된 배열이 반환됩니다 ... 이유는 무엇입니까, 건배 남자js 버블 정렬이 모든 요소를 ​​올바르게 처리하지 않습니다.

this.bubbleSort = function (elements) { 

     //Loop through to the second to last index. By the time we get to the last index, its already //been compared with what’s in front of it 
     var hasHadChange; 
     for (var x = 0; x < elements.length - 1; x++) { 
      hasHadChange = false; 

      //Loop through to the second to last index. 
      for (var y = 0; y < elements.length - 1; y++) { 

       //Check the current item(x) in the array plus the item next to current item (x+1), if its larger 
       if (elements[y] > elements[y + 1]) { 

        //Acknowledge there has been a change 
        hasHadChange = true; 

        //Swap the items around 
        var temp = elements[y]; 
        elements[y] = elements[y + 1]; 
        elements[y + 1] = temp; 
        //This continues until the largest value has bubbled to the right 
       } 
      } 
     } 
     return elements; 
    } 
+0

이상한 효과를 유발하는 두 루프에서 동일한 변수 이름 (x)을 사용하고 있습니다. 그들 중 하나를 변경하십시오. hasHadChange를 사용하지 않고 중요성을 파악하고 사용하십시오. – dsharew

+0

빠른 답장을 보내 주셔서 감사합니다. ive는 x와 Y로 vars를 구분하지만, 여전히 루프가 끊어집니다. 어떤 순서로든 내 값을 반환해도 동일한 결과가 반환됩니다. –

+0

그래서 위 코드를 새 것으로 업데이트하십시오. 다른 버그가 있는지보십시오. – dsharew

답변

0

내부 및 외부 루프에서 별도의 변수를 사용해야합니다. 대신 내부 루프에 y을 사용하면 정확한 답을 얻을 수 있습니다.

var bubbleSort = function (elements) { 

    //Loop through to the second to last index. By the time we get to the last index, its already //been compared with what’s in front of it 
    var hasHadChange; 
    for (var x = 0; x < elements.length - 1; x++) { 
     hasHadChange = false; 

     //Loop through to the second to last index. 
     for (y = 0; y < elements.length - 1; y++) { 

      //Check the current item(x) in the array plus the item next to current item (x+1), if its larger 
      if (elements[y] > elements[y + 1]) { 

       //Acknowledge there has been a change 
       hasHadChange = true; 

       //Swap the items around 
       var temp = elements[y]; 
       elements[y] = elements[y + 1]; 
       elements[y + 1] = temp; 
       //This continues until the largest value has bubbled to the right 
      } 
     } 
    } 
    return elements; 
} 

이 뒤에 그 이유는 변수 게양입니다.

변수가 선언되면 두 부분으로 나뉩니다. 한 부분이 범위의 맨 위로 이동하고 다른 부분은 위치에 유지됩니다. 이 코드에서 무슨 일이 있었는지입니다

function foo() { 
    var x = undefined; //Declaration of x is hoisted 
    var y = undefined; //Declaration of y is hoisted 
    if (false) { 
     x = 1; //Assignment still occurs where we intended 
    } 
    y = 1; //Assignment still occurs where we intended 
} 

: 같은 예를 들어,

function foo() { 
    if (false) { 
     var x = 1; 
    } 
    var y = 1; 
} 

보일 것이다. 두 루프에서 같은 변수를 사용하면 서로 다른 값을 덮어 씁니다. 따라서 결과.

ECMAScript standard 5.1에서 :

변수 문은 10.5에 정의 된대로 생성되는 변수를 선언합니다. 변수는 생성 될 때 undefined로 초기화됩니다. Initialiser가있는 변수에는 변수가 만들어 질 때가 아니라 VariableStatement가 실행될 때 AssignmentExpression 값이 할당됩니다.

자세한 내용은 this MDN doc을 참조하십시오. 토픽 var hoisting을 찾으십시오. 블록 레벨 범위가 let를 사용

업데이트

, 당신은 두 루프의 변수 x을 가질 수 있습니다. 당신은 모두 사이클에 대해 동일한 제어 변수 x을 사용하는

var bubbleSort = function (elements) { 

    //Loop through to the second to last index. By the time we get to the last index, its already //been compared with what’s in front of it 
    var hasHadChange; 
    for (var x = 0; x < elements.length - 1; x++) { 
     hasHadChange = false; 

     //Loop through to the second to last index. 
     for (let x = 0; x < elements.length - 1; x++) { 

      //Check the current item(x) in the array plus the item next to current item (x+1), if its larger 
      if (elements[x] > elements[x + 1]) { 

       //Acknowledge there has been a change 
       hasHadChange = true; 

       //Swap the items around 
       var temp = elements[x]; 
       elements[x] = elements[x + 1]; 
       elements[x + 1] = temp; 
       //This continues until the largest value has bubbled to the right 
      } 
     } 
    } 
    return elements; 
} 
+0

변수가 자연적으로 게양되었지만 실제로는 관련이 없습니다.변수 범위를 생각하고 있습니까? – Guffa

+0

예. 답변을 업데이트했습니다. – vjdhama

+0

내가 let을 사용하면 구문 오류가 발생합니다 ... –

1

내부 루프와 외부 루프에 별도의 변수를 사용해야합니다. 내부 루프를 종료하면 x이 길이와 같아 지므로 외부 루프도 종료됩니다.

0

는, 예를 들어 같은 xy을 다른를 사용해야합니다.

관련 문제