2017-02-16 3 views
-4

버블 정렬을 코딩하는 기능을 보여주는 클래스 용 프로그램을 작성하고 있습니다. 나는 며칠 동안 그 일을 해왔으며 그것을 얻지 못하는 것 같습니다. 적어도 지금은 컴파일되지만 예외가 발생합니다.
배열에있는 요소의 실제 스와핑에 문제가있는 부분에 대해 주석을 달았습니다.버블 정렬에서 예외가 throw됩니다.

프로그램은 20 개의 randoms 정수 배열을 생성 한 다음 버블 정렬을 사용하여 정렬합니다. 완료 될 때까지 각 패스를 인쇄합니다.

import java.util.*; 


public class BubbleSorting { 


public static void bubbleSort(ArrayList<Integer> arr) { 
    int n = arr.size(); 
    int temp = 0; 

    for (int i = 0; i < n; i++) { 

    //this is the chunk of code that I am having problems with 
    for (int j = i; j < (n-1); j++) { 
     if (arr.get(n-1) < arr.get(j)) 
      temp = arr.get(j-1); 
      arr.set(j-1, arr.get(j)); 
      arr.set(j, temp); 
    } 

    } 
} 

private static void printOut(int pass, ArrayList<Integer> array) { 
    System.out.print("Pass " + pass + ": "); 
    for (int i = 0; i < array.size() - 1; i++) { 
    System.out.print(array.get(i) + ", "); 
    } 

    System.out.print(array.get(array.size() - 1) + "."); 
    System.out.println(); 


} 


public static void main(String[] args) { 
    ArrayList<Integer> array = new ArrayList<Integer>(); 
    Scanner sc = new Scanner(System.in); 
    String userInput = ""; 
    boolean endLoop = false; 

    do{ 
    try{ 

     for (int i = 0; i < 20; i++) { 
      int element = (int)(1000.0 * Math.random()); 
      array.add(element); 
     } 
     System.out.print("\nUnsorted Array: "); 

       //Displays the unsorted ArrayList 
     for (int i = 0; i < array.size() - 1; i++) { 
      System.out.print(array.get(i) + ", "); 
     } 

     System.out.print(array.get(array.size() - 1) + "."); 
     System.out.println(); 
     bubbleSort(array); 
    } 
    catch (IndexOutOfBoundsException e) { 
     System.out.println("\nThere is an out of bounds error in the ArrayList."); 
    } 



    System.out.print("\nEnter Y to continue or N to quit: "); 
     userInput = sc.nextLine(); 

    if (userInput.equalsIgnoreCase("Y")) { 
     endLoop = false; 

    } 
    else if (userInput.equalsIgnoreCase("N")) { 
     endLoop = true; 
    } 

    else { 
     System.out.println("\nYou did not enter Y or N."); 
     System.out.println("Please try again."); 
    } 

    }while(endLoop == false); 


    } 
} 
+0

예외는 무엇입니까? – bejado

+0

디버거를 사용해 보셨습니까? 또는 코드를 직접 작성 하시겠습니까? 예를 들어'i = j = 0' 일 때 엔트리를 바꿔야 할 때 어떻게 될까요? –

+0

i = 0이고 j = 0 일 때, 인덱스는 경계를 벗어난 인덱스 = -1이됩니다. 귀하의 ** j ** ** ** i **부터 시작됩니다. – HappyHal

답변

0

다음 코드를 사용해보십시오 :

public static void bubbleSort(ArrayList<Integer> list){ 
     for(int i = 0; i < list.size(); i++) { 
      for(int j = 1; j < (list.size() -i); j++) { 
       if(list.get(j - 1) > list.get(j)) { 
        int temp = list.get(j-1); 
        list.set(j-1, list.get(j)); 
        list.set(j, temp); 
       }     
      } 
     }  
    } 

을 당신 한 첫 번째 루프의 1에서 2 실수 ... 그 for(int j = 1; j < (list.size() -i); j++) 당신이 int j=i을 썼다하고있는 {} 괄호를 포함하지 않았다되는 두 번째 if loop condition.Cheers

0

소년은 if 문 안의 브래킷을 놓쳤다. 첫 번째 문

//this is the chunk of code that I am having problems with 
       for (int j = i; j < (n - 1); j++) { 
        if (arr.get(n - 1) < arr.get(j)) {//<------here this one 
         temp = arr.get(j - 1); 
         arr.set(j - 1, arr.get(j)); 
         arr.set(j, temp); 
        }//<----this too 
       } 

후 당신이 브래킷을 넣어하지 않는 경우로 간주됩니다.

+0

아직도 그것은 정렬되지 않을 것이다. .. 이것은 단지 indexoutofbondsexception을 피할 것이지만 정렬을하지 않을 것이다. for 루프에서 그 int j = 1 아닌 j = i ... – Akshay

0

거품 정렬 방법에 대한 오해가있을 수 있습니다. 이 예에서 배열을 사용하는 경우, 지금

for (int i = 0; i < n; i++) { 

    //this is the chunk of code that I am having problems with 
    for (int j = i; j < (n-1); j++) { 
     if (arr.get(n-1) < arr.get(j)) 
      temp = arr.get(j-1); 
      arr.set(j-1, arr.get(j)); 
      arr.set(j, temp); 
    } 

} 

: 여기

Let us take the array of numbers "5 1 4 2 8", and sort the array from lowest 
number to greatest number using bubble sort. In each step, elements written 
in bold are being compared. Three passes will be required. 

First Pass 
(5 1 4 2 8) (1 5 4 2 8), Here, algorithm 
compares the first two elements, and swaps since 5 > 1. 
(1 5 4 2 8) (1 4 5 2 8), Swap since 5 > 4 
(1 4 5 2 8) (1 4 2 5 8), Swap since 5 > 2 
(1 4 2 5 8) (1 4 2 5 8), Now, since these elements are already in order 
(8 > 5), algorithm does not swap them. 

Second Pass 
(1 4 2 5 8) (1 4 2 5 8) 
(1 4 2 5 8) (1 2 4 5 8), Swap since 4 > 2 
(1 2 4 5 8) (1 2 4 5 8) 
(1 2 4 5 8) (1 2 4 5 8) 
Now, the array is already sorted, but the algorithm does not know if it is 
completed. The algorithm needs one whole pass without any swap to know it is 
sorted. 

Third Pass 
(1 2 4 5 8) (1 2 4 5 8) 
(1 2 4 5 8) (1 2 4 5 8) 
(1 2 4 5 8) (1 2 4 5 8) 
(1 2 4 5 8) (1 2 4 5 8) 

이제 (this link에서 촬영) 버블 정렬이 작동하는 방법의 예이며, 여기에 코드에 생각의 라인을 비교 (5 1 4 2 8) 그리고 코드에 연결하면 8을 모든 주어진 숫자와 비교해 버릴 것입니다. 그리고 8이 이미 가장 크기 때문에 if 문은 항상 거짓이됩니다. 정렬이 발생하지 않습니다. 대신 한 번에 두 개의 인접한 인덱스를 비교하고 스왑이 발생했는지 여부를 나타내는 부울을 사용하십시오. 이런 종류의 기능성을 감안할 때 정렬은 가능한 한 배열 끝까지 가장 큰 숫자를 계속 교체합니다. 따라서 스왑이 없으면 배열이 정렬 된 것입니다. 따라서 내부 루프는 이미 정렬 된 부분으로 이동하기 만하면됩니다. 정렬 된 값을 비교하면 정렬이 일찍 종료됩니다. 이 사고 방식을 사용하여 코드에 적용하십시오.