[C] 퀵 정렬(Quick Sort)

#include <stdio.h>
#include <stdlib.h>

#define SWAP(x, y, t) ((t) = (x), (x) = (y), (y) = (t))

int partition(int list[], int left, int right)
{
	int pivot = 0, temp = 0;
	int low = 0, high = 0;

	low = left;
	high = right + 1;
	pivot = list[left];

	do
	{
		do
		{
			low++;
		}while(low <= right && list[low] < pivot);

		do
		{
			high--;
		}while(high >= left && list[high] > pivot);

		if(low < high)
		{
			SWAP(list[low], list[high], temp);
		}
	}while(low < high);

	SWAP(list[left], list[high], temp);

	return high;
}

void quick_sort(int list[], int left, int right)
{
	if(left < right)
	{
		int q = partition(list, left, right);
		quick_sort(list, left, q - 1);
		quick_sort(list, q + 1, right);
	}
}

int main()
{
	FILE * fp = NULL;
	int cnt = 0;
	int temp = 0;
	int * no = NULL;
	int i = 0;

	fp = fopen("data.txt", "r");
	if(fp == NULL)
	{
		printf("파일 개방 실패!!!\n");
		return 0;
	}

	while(!feof(fp))
	{
		fscanf(fp, "%d", &temp);
		cnt++;
	}
	rewind(fp);

	no = (int*)malloc(sizeof(int) * cnt);

	for(i = 0; i < cnt; i++)
	{
		fscanf(fp, "%d", &no[i]);
	}

	printf("Quick Sort 정렬 전 :\n");
	for(i = 0; i < cnt; i++)
	{
		printf("%-3d", no[i]);
	}
	printf("\n\n");

	quick_sort(no, 0, cnt - 1);

	printf("\n\nQuick Sort 정렬 후 :\n");

	for(i = 0; i < cnt; i++)
	{
		printf("%-3d", no[i]);
	}
	printf("\n");

	free(no);
	fclose(fp);

	return 0;
}

댓글

이 블로그의 인기 게시물

[NSIS] 32비트와 64비트 모듈 등록하는 법. (regsvr32)

[Visual Studio] Windows 7 에서 Visual Studio 6.0 디버그 시 프로세스 좀비되는 증상 해결 방법