"병합정렬 구현"의 두 판 사이의 차이

(같이 보기)
(C)
4번째 줄: 4번째 줄:
 
<source lang='c'>
 
<source lang='c'>
 
#include <stdio.h>
 
#include <stdio.h>
#define SIZE 10
+
void merge_sort(int arr[], int size, int low, int high) {
int a[SIZE] = {3,4,2,1,7,5,8,9,0,6};
+
if(low >= high) return;
int size = SIZE;
+
int mid = (low+high)/2;
int b[SIZE-1];
+
merge_sort(arr, size, low, mid);
void merge(int low, int mid, int high) {
+
merge_sort(arr, size, mid+1, high);
int l1, l2, i;
+
 +
//merge
 +
    int temp[size-1], l1, l2, i;
 
for(l1=low, l2=mid+1, i=low; l1<=mid && l2<=high; i++) {
 
for(l1=low, l2=mid+1, i=low; l1<=mid && l2<=high; i++) {
if(a[l1]<=a[l2]) b[i]=a[l1++];
+
if(arr[l1]<=arr[l2]) temp[i]=arr[l1++];
else b[i]=a[l2++];
+
else temp[i]=arr[l2++];
 
}
 
}
while(l1 <= mid) b[i++]=a[l1++];
+
while(l1 <= mid) temp[i++]=arr[l1++];
while(l2 <= high) b[i++]=a[l2++];
+
while(l2 <= high) temp[i++]=arr[l2++];
for(i=low; i<=high; i++) a[i]=b[i];
+
for(i=low; i<=high; i++) arr[i]=temp[i];
}
 
void merge_sort(int low, int high) {
 
if(low >= high) return;
 
int mid = (low+high)/2;
 
merge_sort(low, mid);
 
merge_sort(mid+1, high);
 
merge(low, mid, high);
 
 
}
 
}
int main() {  
+
int main() {
merge_sort(0, SIZE-1);
+
    int arr[] = {3,4,2,1,7,5,8,9,0,6,100,10};
for(int i=0; i<SIZE; i++) printf("%d ", a[i]);
+
    int size = sizeof(arr)/sizeof(int);
// 0 1 2 3 4 5 6 7 8 9
+
merge_sort(arr, size, 0, size-1);
 +
for(int i=0; i<size; i++) printf("%d ", arr[i]);
 +
// 0 1 2 3 4 5 6 7 8 9 10 100
 
}
 
}
 
</source>
 
</source>

2018년 7월 15일 (일) 18:08 판

1 C

#include <stdio.h>
void merge_sort(int arr[], int size, int low, int high) {
	if(low >= high) return;
	int mid = (low+high)/2;
	merge_sort(arr, size, low, mid);
	merge_sort(arr, size, mid+1, high);
	
	//merge
    int temp[size-1], l1, l2, i;
	for(l1=low, l2=mid+1, i=low; l1<=mid && l2<=high; i++) {
		if(arr[l1]<=arr[l2]) temp[i]=arr[l1++];
		else temp[i]=arr[l2++];
	}
	while(l1 <= mid) temp[i++]=arr[l1++];
	while(l2 <= high) temp[i++]=arr[l2++];
	for(i=low; i<=high; i++) arr[i]=temp[i];
}
int main() {
    int arr[] = {3,4,2,1,7,5,8,9,0,6,100,10};
    int size = sizeof(arr)/sizeof(int);
	merge_sort(arr, size, 0, size-1);
	for(int i=0; i<size; i++) printf("%d ", arr[i]);
	// 0 1 2 3 4 5 6 7 8 9 10 100 
}

2 같이 보기

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