Sorting Algorithm

Insertion Sort Algorithm

Untitled

Untitled

#include <iostream>
using namespace std;

int* insertionSort(int* A, int n){
	int i, j, key;
	for(j = 1; j<n; j++){
		key = A[j];
		i = j-1;
		while(i>=0 && A[i]>key){
			A[i+1] = A[i];
			i--;
		}
		// for(i = j-1; i>=0 && A[i]>key;i--){
		// 	A[i+1] = A[i];
		// }
		A[i+1] = key;
		for(int ind = 0; ind<n; ind++){
		cout<<A[ind]<<" ";
		}
		cout<<endl;
	}
	return A;
}

int main() {
	int a[] = {5, 2, 4, 6, 1, 3};
	int n = sizeof(a)/sizeof(a[0]);

	for(int i = 0; i<n; i++){
		cout<<a[i]<<" ";
	}
	cout<<endl;
	int* result;
	result = insertionSort(a, n);
	for(int i = 0; i<n; i++){
		cout<<result[i]<<" ";
	}
	cout<<endl;
}

/* 출력결과
5 2 4 6 1 3 
2 5 4 6 1 3 
2 4 5 6 1 3 
2 4 5 6 1 3 
1 2 4 5 6 3 
1 2 3 4 5 6 
1 2 3 4 5 6
*/

Insertion Sort 수행시간 분석

Untitled

$\therefore T(n)=c_1n + c_2(n-1) + c_3(n-1) + \sum_{j=1}^{n-1} \{ c_4t_j + c_5(t_j-1) + c_6(t_j-1) \} + c_7(n-1)\newline = n(c_1+c_2+c_3-c_5-c_6+c_7) - (c_2+c_3-c_5-c_6+c_7) + (c_4+c_5+c_6)\sum_{j=1}^{n-1}t_j$

증가 차수