본문 바로가기

코딩 테스트

백준 24060 병합 정렬

#include <iostream>
#include <vector>

using namespace std;

int n, m;

int countAnswer = 0;
int answer = 0;

void merge(vector<int>&, int, int, int);

void merge_sort(vector<int>& arr, int start, int end)
{
	if (start < end)
	{
		int mid = (start + end) * 0.5f;
		merge_sort(arr, start, mid);
		merge_sort(arr, mid + 1, end);
		merge(arr, start, mid, end);
	}
}

void merge(vector<int>& arr, int start, int mid, int end)
{
	int i = start;
	int j = mid + 1;
	int t = 0;
	int size = end - start + 1;
	vector<int> temp(size);
	while (i <= mid && j <= end)
	{
		if (arr[i] <= arr[j])
		{
			temp[t] = arr[i];
			i++;
			t++;
		}
		else
		{
			temp[t] = arr[j];
			j++;
			t++;
		}
	}

	while (i <= mid)
	{
		temp[t] = arr[i];
		t++;
		i++;
	}

	while (j <= end)
	{
		temp[t] = arr[j];
		t++;
		j++;
		
	}

	t = 0;
	for (int k = start; k <= end; ++k, ++t)
	{
		arr[k] = temp[t];
		countAnswer++;
		if (countAnswer == m)
		{
			answer = arr[k];
		}
	}
}

int main(void)
{
	ios_base::sync_with_stdio(false);
	cin.tie(0);	cout.tie(0);

	cin >> n >> m;

	vector<int> arr(n);

	for (int i = 0; i < n; ++i)
	{
		cin >> arr[i];
	}

	merge_sort(arr, 0, arr.size() - 1);

	if (countAnswer < m)
	{
		cout << -1;
	}
	else
	{
		cout << answer;
	}

	return 0;
}

'코딩 테스트' 카테고리의 다른 글

백준 투포인터 2230  (0) 2024.11.01
백준 LIS 2 - 12015  (1) 2024.11.01
백준 11053 LIS 1  (0) 2024.11.01
백준 11727 타일링  (0) 2024.10.15
백준 17829 - 222풀링  (0) 2024.09.09