2016-11-20 1 views
3

"이름"이라는 객체 변수에 의해 객체의 arraylist를 알파벳 순으로 정렬하려고합니다.왜 내 거품 정렬 작업을하지 않습니까? - Java

public void sortName() 
    { 
     int j; 

     for (j = 0; j < theBatters.size()-1; j++) 
     { 
      System.out.println(theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j+1).getName())); 
      if (theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j).getName()) > 0) 
      {            // ascending sort 
       Collections.swap(theBatters, j, j+1); 
       j=0; 
      } 
     } 
    } 

나는 문제가 스왑 내가이 sortName를 사용한 후에 나는 ArrayList를 인쇄 할 때를 위해, 사용되는 라인과 함께 할 수있는 뭔가가 생각() 메소드의 모든입니다 : 여기에 내가 그렇게 쓴 코드는 이 가정하면 0보다 큰 값을 반환하는이 라인에도 불구하고 동일한 순서는 :

System.out.println(theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j+1).getName())); 
+0

if 문에서 get (j)과 get (j)를 다시 비교하는 이유는 무엇입니까? –

+2

@AndrewtheProgrammer가 버그를 발견했습니다. compareToIgnoreCase 메소드의'if' 문에'theBatter.get (j + 1)'을 넣고 싶습니다. –

+0

기꺼이 도울 수있어 기쁘다. 그런 단순한 실수는 단지 그것을 보면서 발견하는 고통이다. –

답변

0

버블 정렬의 매우 이름이 정렬 및 정렬되지 않은 항목의 거품이 있음을 의미한다. 당신은이 사실을 잊어 버렸을뿐입니다. 여기에 노력하고 있습니다 (희망) 코드 :

public void sortName() 
     { 

      for (int i = 0; i < theBatters.size()-1; i++) // bigger outer bubble 
      for (int j = i+1; j < theBatters.size()-1; j++) // smaller inner bubble 
      {     System.out.println(theBatters.get(i).getName().compareToIgnoreCase(theBatters.get(j).getName())); 
       if (theBatters.get(i).getName().compareToIgnoreCase(theBatters.get(j).getName()) > 0) 
       {            // ascending sort 
        Collections.swap(theBatters, i, j); 
        // j=0; // Not necessary and confusing. It is already in good order 
       } 
      } 
     } 
관련 문제