[Java] Sort 정렬 알고리즘

동민·2021년 3월 11일
0
public class Sort_algoritm {

	// 버블정렬
	public static void bubblesort(int[] arr) {
		System.out.println("bubble sort");

		int temp = 0;
		for (int i = 0; i < arr.length - 1; i++) {
			for (int j = arr.length - 1; j > i; j--) {

				if (arr[j - 1] > arr[j]) {
					temp = arr[j - 1];
					arr[j - 1] = arr[j];
					arr[j] = temp;
				}

			}
		}

	}

	// 선택정렬
	public static void selectsort(int[] arr) {
		System.out.println("selection sort");

		int temp = 0;
		int min = 0;

		for (int i = 0; i < arr.length - 1; i++) {

			min = i;

			for (int j = i + 1; j < arr.length; j++) {

				if (arr[min] > arr[j]) {

					min = j;

				}

			}
			temp = arr[min];
			arr[min] = arr[i];
			arr[i] = temp;
		}

	}
	
    	// 삽입정렬
	public static void insertionsort(int[] arr) {
		System.out.println("insertion sort");

		int temp = 0;
		int j = 0;

		for (int i = 1; i < arr.length; i++) {

			temp = arr[i];
			for (j = i - 1; j >= 0 && temp < arr[j]; j--) {

				arr[j + 1] = arr[j];

			}
			arr[j + 1] = temp;

		}

	}

	public static void main(String[] args) {

		int[] arr = { 1, 5, 7, 3, 5, 13, 51, 2, 41 };

		for (int i = 0; i < arr.length; i++) {

			System.out.print(arr[i] + " ");
		}
		System.out.println("\n-------------------------");

//		bubblesort(arr);
//		selectsort(arr);
		insertionsort(arr);

		for (int i = 0; i < arr.length; i++) {

			System.out.print(arr[i] + " ");
		}

	}

}
profile
BE Developer

0개의 댓글