/* ---------- 선택정렬(Selection Sort)---------------*/ import java.util.*;
public class SelectionSort {
public static void main(String[] args) { int numArray[] = new int [10];
for(int i = 0; i < 10; i++ ) { numArray[i] = (int)(Math.random()*100+1); // 1부터 100까지의 난수발생 }
SelectionSortASC(numArray); //오름차순 정렬 System.out.println("오름차순 정렬: "); for(int j=0; jSystem.out.print(numArray[j] + " "); }
System.out.println("\r\n");
SelectionSortDESC(numArray); //내림차순 정렬
System.out.println("내림차순 정렬: ");
for(int j=0; jSystem.out.print(numArray[j] + " "); } }
// --- numArray를 오름차순 정렬 private static void SelectionSortASC(int[] numArray) {
for(int i = 0; i < numArray.length-1; i++ ) { int minIndex = i; int temp = numArray[i];
// i번째 이후의 값들중 최소값을 Temp에 구해놓는다 for(int j=i+1; j < numArray.length; j++ ){ if ( numArray[j] < temp) { minIndex = j; temp = numArray[j]; } } numArray[minIndex] = numArray[i]; // numArray[i]의 값과 temp의 값을 교환 numArray[i] = temp; }
}
// --- numArray를 내림차순 정렬 private static void SelectionSortDESC(int[] numArray) {
for(int i = 0; i < numArray.length-1; i++ ) { int maxIndex = i; int temp = numArray[i];
// i번째 이후의 값들중 최대값을 Temp에 구해놓는다 for(int j=i+1; j < numArray.length; j++ ){ if ( numArray[j] > temp) { maxIndex = j; temp = numArray[j]; } } numArray[maxIndex] = numArray[i]; // numArray[i]의 값과 temp의 값을 교환 numArray[i] = temp; }
} } |