takenname   2년 전

다른 분들의 접근을 보고 저는 다르게 접근해 보고 싶다는 생각을 해보았습니다. 그래서 Dictionary 자료형을 직접 구현하기로 결정하고 구조체로 구현을 했습니다.

  • Dictionary의 key: (idx, len)
  • Dictionary의 value: words

정렬은 비재귀 병합 정렬을 활용했습니다.

결과적으로 글자 수에 대한 정렬은 이루어졌지만, 알파벳순 정렬에는 문제가 있습니다. 그러나 어디에 문제가 있는지 혼자서 찾기가 어렵습니다. 이 초보자에게 작은 도움 부탁드립니다.

예시 경우를 남깁니다.

takenname   2년 전

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

struct Dictionary
{
	int idx, len;
	char words[51];
};

bool is_first(struct Dictionary dict[], int idx_1, int idx_2)
{
	if (dict[idx_1].len < dict[idx_2].len)
	{
		return true;
	}
	else if (dict[idx_1].len > dict[idx_2].len)
	{
		return false;
	}
	else
	{
		return strcmp(dict[idx_1].words, dict[idx_2].words) < 0;
	}
}

void merge_sort(struct Dictionary dst[], struct Dictionary tmp[], int size)
{
	int rght, rend;
	int i, j, m;

	for (int k = 1; k < size; k *= 2)
	{
		for (int left = 0; left + k < size; left += 2 * k)
		{
			rght = left + k;
			rend = rght + k;
			if (rend > size)
			{
				rend = size;
			}
			m = left, i = left, j = rght;

			for (; i < rght && j < rend; m++)
			{
				if (is_first(dst, i, j))
				{
					tmp[m] = dst[i];
					i++;
				}
				else
				{
					tmp[m] = dst[j];
					j++;
				}
			}

			for (; i < rght; i++, m++)
			{
				tmp[m] = dst[i];
			}

			for (; j < rend; j++, m++)
			{
				tmp[m] = dst[j];
			}

			for (m = left; m < rend; m++)
			{
				dst[m] = tmp[m];
			}
		}
	}
}

int main()
{
	int n;
	scanf("%d", &n);

	struct Dictionary* String = (struct Dictionary*)malloc(n * sizeof(struct Dictionary));
	struct Dictionary* tmp = (struct Dictionary*)malloc(n * sizeof(struct Dictionary));

	for (int i = 0; i < n; i++)
	{
		char str[51];
		scanf("%50s", str);
		int len = (int)strlen(str);

		String[i].idx = i;
		String[i].len = len;
		strcpy(String[i].words, str);
	}

	merge_sort(String, tmp, n);

	for (int i = 0; i < n; i++)
	{
		if (i == 0 || strcmp(String[i - 1].words, String[i].words))
		{
			puts(String[i].words);
		}
	}

	free(String);
	free(tmp);
	return 0;
}

댓글을 작성하려면 로그인해야 합니다.