java

Java/Selection Sort/선택정렬

MyaZ 2020. 1. 28. 13:58

Selection sort 

: is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.

 

선택정렬

:적은 데이터를 정렬하는데 유용. 

 

참조이미지

https://www.w3resource.com/w3r_images/selection-sort.png

import java.util.Arrays;

public class SelectionSort {
	
	public static void selectionSort(int[]_arr) {
		//마지막값은 비교대상이 없으므로 배열길이 -1까지만 비교가 이루어진다.
		for(int i=0;i<_arr.length-1;i++) {//i를 기준점으로 j와 비교
			int minIdx=i;
			
			//아래 for문이 끝나면 현재기준공간에 들어갈 위치가 결정된다.
			for (int j=i+1;j<_arr.length;j++) {
				if(_arr[j]<_arr[minIdx])//부등호에 따라 내림차순 오름차순 결정.
					minIdx=j;
					
			}
			//_arr배열의 i값과 minIdx값을 교체한다.
			swap(_arr,i,minIdx);
			
		}
	}
	public static void swap(int[]_a, int base, int mIdx) {
		int temp=_a[base];
		_a[base]=_a[mIdx];
		_a[mIdx]=temp;
		
	}
	
	public static void main(String[] args) {
		int[] arr= {77,99,25,2,10};
		System.out.println(Arrays.toString(arr));
		selectionSort(arr);
		System.out.println(Arrays.toString(arr));
		
		int[] arr1= {77,99,25,2,10,4,523,244,22,1,3};
		System.out.println(Arrays.toString(arr1));
		selectionSort(arr1);
		System.out.println(Arrays.toString(arr1));
	}
}