#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <time.h>
void print_array(int *x, int n);
int* scaffolding(int n);
void quicksort(int *x, int n);
void swap(int *, int *);
int main() {
int *x, n, i;
printf("배열 크기 : ");
scanf("%d", &n);
x = scaffolding(n);
print_array(x, n);
quicksort(x, n);
print_array(x, n);
return 0;
}
void quicksort(int *x, int n) {
if(n <= 1)
return;
int i, m = 0;
for(i = 1; i < n ; ++i) {
if(x[0] > x[i]) {
swap(&x[++m], &x[i]);
}
}
swap(&x[m], &x[0]);
quicksort(x, m);
quicksort(x+m+1, n-m-1);
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void print_array(int *x, int n) {
int i;
for(i = 0; i < n; ++i)
printf("%d ", x[i]);
printf("\n");
}
int* scaffolding(int n) {
srand((unsigned) time(NULL));
int *x, i;
x = (int *)malloc(n * sizeof(int));
for(i = 0; i < n; ++i)
x[i] = rand() % n;
return x;
}
밑의 함수는 정렬하는 부분만 다른 알고리즘으로 풀어봤다.
void quicksort(int *x, int n) {
if(n <= 1)
return;
int l = 0, u = n;
while(1) {
do {++l;} while(x[0] > x[l] && l < n);
do {--u;} while(x[0] <= x[u] && u > 0);
if(u < l)
break;
swap(&x[l], &x[u]);
}
swap(&x[0], &x[u]);
quicksort(x, u);
quicksort(x+u+1, n-u-1);
}
'Computer Science > Algorithm' 카테고리의 다른 글
Quick Select - Find k-th item in an unsorted array. (0) | 2014.06.29 |
---|---|
quick sort - Java (0) | 2011.05.30 |
insertion sort - c (0) | 2011.05.28 |
insertion sort - Java (0) | 2011.05.26 |
binary search - Java (0) | 2011.05.17 |