java void 함수 통해서 삽입한 숫자 오름차/내림차순으로 정렬하는 프로그램 만들기
import java.util.Arrays;
import java.util.Scanner;
public class Sorting {
int number[];
int updown;
void input() {
Scanner sc =new Scanner(System.in); System.out.print("몇개 정렬?");
int count = sc.nextInt();
number = new int[count];
for (int i = 0; i < number.length; i++) {
System.out.print((i+1)+"번째 수 = ");
number[i] = sc.nextInt();
}
System.out.println("오름(1)/내림(2) =");
updown =sc.nextInt();
}
void sorting() {
for (int i = 0; i < number.length-1; i++) {
for (int j = i+1; j < number.length; j++) {//n[i]가 n[j]보다 앞에 있다
if(updown==1) {
if(number[i]>number[j]) { //만약 오름차순이라면 비교당하는 대상이 클때 뒤로 보낸다
swap(i,j);
}
}
else {
if(number[i]<number[j]) { //내림차순이라면 이라면 비교당하는 대상이 작을때 뒤로 보낸다
swap(i,j);
}
}
}
}
}
void swap(int i, int j) {
int temp =number[i];
number[i]=number[j];
number[j]=temp;
}
void result() { System.out.println(Arrays.toString(number));
}
}
위의 Sorting 클래스를 다른 외부 클래스에서 불러와 사용할때
public class MainClass {
public static void main(String[] args) {
Sorting sort = new Sorting(); //객체 초기화 필수. 새로운 객체명은 sort
sort.input(); //sort에 있는 input 함수 출력
sort.sorting();
sort.result();
}
}