Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

JS Coding

[Java] 초급자바 소트정렬 코드 본문

Java

[Java] 초급자바 소트정렬 코드

JSKJS 2024. 1. 5. 14:22
public class SortExample {

	public static void main(String[] args) {
		BubbleSort bubble = new BubbleSort(new int[] { 27, 15, 90, 63, 56, 70 });	
		System.out.println(Arrays.toString(bubble.source));
		
		int[] sortedArray = bubble.sort();
		System.out.println("버블정렬 결과 : " + Arrays.toString(sortedArray));
		
		SelectionSort selection = new SelectionSort(new int[] { 27, 15, 90, 63, 56, 70 });
		sortedArray = selection.sort();
		System.out.println("선택정렬 결과 : " + Arrays.toString(sortedArray));
	}
}

class BubbleSort {  // 1번과 2번을 비교해서 작은숫자를 앞으로 옮기고 순차적 비교를 하면서 정렬
	int[] source;

	BubbleSort(int[] source) {
		this.source = source;
	}

	public int[] sort() {
		boolean flag = true; // 개선된 버블소트
		for (int i = 0; i < source.length - 1; i++) { // 회전 수
			flag = true;// 개선된 버블소트
			for (int j = 0; j < source.length - 1 - i; j++) {
				if (source[j] > source[j + 1]) {
					int temp = source[j];
					source[j] = source[j + 1];
					source[j + 1] = temp;
					flag = false;// 개선된 버블소트
				}
			}
			if (flag)
				break;// 개선된 버블소트
		}
		return source;
	}
}
class SelectionSort { // 1번을 순차적으로 비교하여 비교 정렬 하고 2번 --5번까지 순차적 비교 하면서 정렬  
		int[] source;

		SelectionSort(int[] source) {
			this.source = source;
		}
		
		public int []  sort() {
			for(int i=0; i<source.length-1;i++) {
				for(int j=i+1; j<source.length-1;j++) {
					if(source[i]>source[j]) {
						int temp=source[i];
						source[i]=source[j];
						source[j]=temp;
					}
				}
			}
			return source;
		}
	}