2014-11-23 3 views
-1

스택에 개체가 4 개 이상이면 내 버블 정렬이 작동하지 않습니다. 어째서? 내가 푸시면 a, b, c. 버블 정렬은 그들을 정렬합니다 : c, b, 올바른지. 그러나 만약 내가 a, b, c, d. 버블 정렬은 다음과 같이 정렬합니다 : a, d, c, b. 만약 내가 a, b, c, d, e가 있다면. 버블 정렬은 다음과 같이 정렬합니다 : a, b, e, d, c, b.목록에 3 개 이상의 개체가있는 경우 내 버블 정렬이 바뀌지 않습니다. JAVA

내 노드 클래스 :

public class Stack implements StackAPI{ 

public Stack(){ 
} 

private Node first = null; 
private int size = 0; 

private class Node implements Comparable<Node>{ 
    String item; 
    Node next; 

    public String getItem(){ 
     return this.item; 
    } 
    public int compareTo(Node other){ 

     if(getItem().compareTo(other.getItem()) > 0){ 
      return 1; 
     } 

     else if(getItem().compareTo(other.getItem()) < 0){ 
      return -1; 
     } 
     else 
      return 0; 
    } 
} 

버블 정렬 기능 :

public void bubbleSort(){ 
    int N = size; 
    boolean swapped = true; 


    while(swapped == true){ 
     Node currentNode = first; 
     swapped = false; 


     for(int i=0; i < N-1; i++){ 
      if(less(currentNode.next, currentNode)){ 

       exch(currentNode); 
       swapped = true; 
      } 

      currentNode = first.next; 
     } 
    } 
} 

덜하고 EXCH 기능 :

private static boolean less(Comparable v, Comparable w){ 
    return v.compareTo(w) < 0; 
} 

private static void exch(Node a) { 
    String swap = a.item; 
    a.item = a.next.item; 
    a.next.item = swap; 
} 
+0

당신은 디버깅을 수행해야합니다. –

+1

시작하려면'compareTo' 메소드를 다음 라인으로 대체하십시오 :'return getItem(). compareTo (other.getItem());'. 따라서 더 짧고 이해하기 쉬워지며, 디버깅을 다른 곳으로 집중시킬 수 있습니다. –

+0

@ erwin-bolwidt 훨씬 더 나쁜 것은 노드 사이의 링크를 변경하는 대신 exch() 메서드에서 노드 값을 변경하는 것입니다. 예, 작동하지만 설계 관점에서 볼 때 – ursa

답변

0

보이는 문제가 여기에 있습니다 :

for(int i=0; i < N-1; i++){ 
     if(less(currentNode.next, currentNode)){ 

      exch(currentNode); 
      swapped = true; 
     } 

     //currentNode = first.next; // <== here? 
     currentNode = currentNode.next; 
    } 

올바른 방법 :

for (Node curr = first, next = curr.next; next != null; next = curr.next) { 
     if (next >= curr) { 
      curr = next; 
      continue; 
     } 
     // update head, if required 
     if (first == curr) { 
      first = next; 
     } 
     // swap elements 
     curr.next = next.next; 
     next.next = curr; 
     swapped = true; 
    } 
+0

물론이지 .. 고마워! – sexytuna