C언어 삽입정렬 구현

(C 삽입정렬 구현에서 넘어옴)

1 개요[편집]

C 삽입정렬 구현
#include <stdio.h>
void insertion_sort(int a[], int size) {
	int i, j, temp;
	for(i=1; i<size; i++) {
		temp = a[i];
		for(j=i-1; j>=0; j--) {
		    if(a[j]<temp) break;
		    a[j+1] = a[j];
		}
		a[j+1] = temp;
	}
}
int main() {
	int arr[] = {9,1,22,4,0,-1,1,22,100,10};
	int size = sizeof(arr)/sizeof(int);
	insertion_sort(arr, size);
	for(int i=0; i<size; i++) printf("%d ", arr[i]);
	// -1 0 1 1 4 9 10 22 22 100 
}
#include <stdio.h>
#define ARRAYSIZE(A) sizeof(A) / sizeof((A)[0])
void insertion_sort(int a[], int size) {
	int i, j, temp;
	for(i=1; i<size; i++) {
		temp = a[i];
		j = i-1;
		while(j>=0 && a[j]>temp) {
			a[j+1] = a[j];
			j--;
		}
		a[j+1] = temp;
	}
}
int main() {
	int arr[] = {9,1,22,4,0,-1,1,22,100,10};
	int size = ARRAYSIZE(arr);
	insertion_sort(arr, size);
	for(int i=0; i<size; i++) printf("%d ", arr[i]);
	// -1 0 1 1 4 9 10 22 22 100 
}
void insertion_sort( int *data, int n ) {
	int i, j, remember;
	i = n-1;
	while( i-- > 0 ) {
		remember = data[(j=i)];
		while( ++j < n && remember > data[j] );
		if( --j == i ) continue;
		memcpy( data+i, data+i+1, sizeof(*data) * (j-i) );
		data[j] = remember;
	}
}

2 같이 보기[편집]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}