0
사용자가 입력 한 값과 임의의 숫자가 될 수있는 배열을 버블 정렬하려고합니다. 그러나 첫 번째 방법은 효과가 없습니다. JOptionPanes를 사용하고 싶습니다만, 문제가 있는지조차 알지 못합니다. 올바르게 컴파일되지만 제대로 실행되지 않습니다.버블 정렬을 JOptionPanes와 함께 사용
이import javax.swing.*;
import java.io.*;
import java.util.*;
public class Gates_sortingBubble{
public static void main(String[] args)throws IOException{
String amountS;
amountS = JOptionPane.showInputDialog(null, "How many numbers would you like to sort?",
"Sorting Arrays", JOptionPane.INFORMATION_MESSAGE);
int amount = Integer.parseInt(amountS);
JOptionPane.showMessageDialog (null, "Please enter " + amount + " numbers you wish to sort.",
"Sorting Arrays", JOptionPane.INFORMATION_MESSAGE);
int[] numbers = new int [amount];
for(int i = 1; i <= amount; i++){
String tempS = JOptionPane.showInputDialog("Number " + i + ": ");
int temp = Integer.parseInt(tempS);
numbers[i] = temp;
}
sort(numbers);
}
public static void sort(int[] tosort){
int[] original = tosort.clone();
int j;
boolean flag = true; //set flag to true to begin first pass
int temp; //to hold the variable
while(flag){
flag= false; //set flag to false awaiting a possible swap
for(j=0; j < tosort.length -1; j++){
if (tosort[ j ] < tosort[j+1]){
temp = tosort[ j ]; //swap the array elements
tosort[ j ] = tosort[ j+1 ];
tosort[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
print(tosort, original);
}
public static void print(int[] sorted, int[] unsorted){
JOptionPane.showMessageDialog (null, "Your original five numbers are: "
+ Arrays.toString(unsorted) + ". \nYour new five numbers are: "
+ Arrays.toString(sorted) + ".", "Sorted Arrays", JOptionPane.INFORMATION_MESSAGE);
}
}
부울 변수'flag'는 이해할 수 없지만 코드의 목적은 어쨌든이 [버블 정렬] (http://www.roseindia.net/java/beginners/arrayexamples/bubbleSort.shtml)을 참조하십시오.). 마지막 한가지 : IOException을 던지는 코드에 아무것도 없다고 생각합니다. –
@OssamaNasser 그것은 알고리즘에서 '스왑 된'체크입니다. 배열이 이미 정렬되어 있거나 정렬 된 것을 발견하면 중지 된 이후로 순진한 구현보다 개선 된 기능입니다. 어쨌든, 나는 왜 OP가 버블 정렬을 사용하고 싶어하는지 알지 못한다. –