본문 바로가기

C/Reference

[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;
}
반응형