본문 바로가기

개발/코딩

선택정렬(Selection Sort)과 버블정렬(Bubble Sort) in C++

#include "SortDemo.h"

void ASortDemo::BeginPlay()
{
	Super::BeginPlay();	
	DoSort();
}

void ASortDemo::DoSort()
{
	int32 Count = 10;// FMath::RandRange(5, 11);
	TArray<int32> ArrSelectionSort, ArrBubbleSort;
	
	//Selection Sort
	ArrSelectionSort.SetNum(Count);
	FillRandomValuesInArray(ArrSelectionSort);	
	UE_LOG(LogTemp, Warning, TEXT("Generated Array For Selection Sort"));
	PrintOutArray(ArrSelectionSort);
	UE_LOG(LogTemp, Warning, TEXT("Selection Sorted Result"));
	SelectionSort(ArrSelectionSort);	
	PrintOutArray(ArrSelectionSort);

	//BubbleSort
	ArrBubbleSort.SetNum(Count);
	FillRandomValuesInArray(ArrBubbleSort);
	UE_LOG(LogTemp, Warning, TEXT("Generated Array For Bubble Sort"));
	PrintOutArray(ArrBubbleSort);
	UE_LOG(LogTemp, Warning, TEXT("Bubble Sorted Result"));
	SelectionSort(ArrBubbleSort);
	PrintOutArray(ArrBubbleSort);

}

void ASortDemo::FillRandomValuesInArray(TArray<int32>& ArrInputArray)
{
	for (int32 i = 0; i < ArrInputArray.Num(); i++)
	{
		ArrInputArray[i] = FMath::RandRange(i, 100);
	}
}

void ASortDemo::PrintOutArray(TArray<int32>& InputArray)
{
	UE_LOG(LogTemp, Warning, TEXT("===================================="));
	FString StringArrValue = TEXT("{ ");
	
	for (int32 i = 0; i < InputArray.Num(); i++)
	{
		StringArrValue += FString::FromInt(InputArray[i]);

		if (i < InputArray.Num() - 1)
		{			
			StringArrValue += TEXT(", ");
		}

	}

	StringArrValue += TEXT(" }");
	UE_LOG(LogTemp, Warning, TEXT("%s"), *StringArrValue);
	UE_LOG(LogTemp, Warning, TEXT("===================================="));
}

void ASortDemo::SelectionSort(TArray<int32>& InputArray)
{
	for (int32 i = 0; i < InputArray.Num() - 1; i++)
	{
		int32 MinIndex = i;
		for (int32 j = i + 1; j < InputArray.Num(); j++) 
		{
			if (InputArray[j] < InputArray[MinIndex])
			{
				MinIndex = j;
			}
		}

		
		int32 Temp = InputArray[MinIndex];
		InputArray[MinIndex] = InputArray[i];
		InputArray[i] = Temp;		
	}
}

void ASortDemo::BubbleSort(TArray<int32>& InputArray)
{
	for (int i = 0; i < InputArray.Num() - 1; i++)
	{
		for (int j = 0; j < InputArray.Num() - i - 1; j++)
		{
			if (InputArray[j] > InputArray[j + 1])
			{
				int32 Temp = InputArray[j];
				InputArray[j] = InputArray[j + 1];
				InputArray[j + 1] = Temp;
			}

		}
	}
}

UE_LOG는 언리얼 C++용 로그 매크로임. 

반응형

'개발 > 코딩' 카테고리의 다른 글

MSYS2를 통해 MinGW 설치하기  (0) 2025.04.19