public class SortAlgorism {
public static void main(String[] args) {
Sort sort = new Sort();
getResult(sort.bubbleSort(getRandom(100)));
getResult(sort.selectionSort(getRandom(100)));
getResult(sort.insertionSort(getRandom(100)));
}
// 단순 출력
public static void getResult(int[] array) {
System.out.print("result => ");
for(int i : array) {
System.out.print(i + " ");
}
System.out.println("");
System.out.println("============================================");
}
// 중복 없는 랜덤 생성기
public static int[] getRandom(int length) {
int[] array = new int[length];
for(int a = 0; a < array.length; a++) {
array[a] = new Random().nextInt(length);
for(int b = 0; b < a; b++) {
if(array[a] == array[b]) {
a--;
}
}
}
System.out.print("array => ");
for(int i : array) {
System.out.print(i + " ");
}
System.out.println("");
return array;
}
}
public class Sort {
// 버블 정렬
public int[] bubbleSort(int[] array) {
long startTime = System.nanoTime();
int temp;
for(int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length - 1; j++) {
if(array[j] > array[j + 1]) {
temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
long endTime = System.nanoTime();
System.out.println("Bubble Sort TIME : " + (endTime - startTime) / 1000.0 + "(ms)");
return array;
}
// 선택 정렬
public int[] selectionSort(int[] array) {
long startTime = System.nanoTime();
int temp;
for(int a = 0; a < array.length; a++) {
for(int b = a + 1; b < array.length; b++) {
if(array[a] > array[b]) {
temp = array[b];
array[b] = array[a];
array[a] = temp;
}
}
}
long endTime = System.nanoTime();
System.out.println("SelectionSort TIME : " + (endTime - startTime) / 1000.0 + "(ms)");
return array;
}
// 삽입 정렬
public int[] insertionSort(int[] array) {
long startTime = System.nanoTime();
int temp;
for(int i = 1; i<array.length; i++) {
temp = array[i];
int j = i;
for(; j > 0 && array[j - 1] > temp; j--) {
array[j] = array[j - 1];
}
array[j] = temp;
}
long endTime = System.nanoTime();
System.out.println("InsertionSort TIME : " + (endTime - startTime) / 1000.0 + "(ms)");
return array;
}
}
오늘은 기본 3개만.....