본문 바로가기
Algorithm

Insertion sort

by orioncsy 2022. 10. 7.
//c++ insertion sort
int MaxLen; //arr 길이
void InsertionSort(int * arr){
	int i,j;
    for(i=1; i<MaxLen; i++){
    	int temp=arr[i];
    	for(j=i-1; j>=0; j--){
        	if(arr[j]>temp) arr[j+1]=arr[j];
            else break;
        }
        arr[j+1]=temp;
    }
}
//java insertion sort
public class Solution { 
  public int[] insertionSort(int[] arr) {
		//두번째 요소부터 정렬 시도
		// 이중 for문으로 정렬 시도
		// 두번째부터 앞의 요소와 비교하여 더 작을 경우 이동하여 더 클 경우에 삽입
		int i,j;
		for(i=1; i<arr.length; i++){
			int temp=arr[i];
			for(j=i-1; j>=0; j--){
				if(arr[j]>temp) arr[j+1]=arr[j];
				else break;
			}
			arr[j+1]=temp;
		}
		return arr;
	}
}

 

'Algorithm' 카테고리의 다른 글

Merge Sort  (0) 2022.10.11
Radix Sort  (0) 2022.10.11
Bubble Sort  (0) 2022.10.06
Quick Sort  (0) 2022.10.06
[알고리즘] Base  (0) 2022.09.28