// Problem :100개의 데이터가 input.txt 파일에 내림차순으로 정렬되어 있다.
// 이 중에서 200을 기준으로 200보다 작은 값의 최대치와 200보다 큰 값의 최소치를 찾고
// 값이 위치한 인덱스를 찾아 콘솔출력하라.
// 단, 검색은 O(logN) 의 복잡도를 가져야 한다, 파일의 내용을 입력받을 때는 O(N)으로 한다.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *inputData; // def. File Handle pointer
int ArrayCenter = 0; // Array of center value Variable.
int ArrayLeft = 0; // Array of left value Variable.
int ArrayRight = 99; // Array of right value Variable.
int MaxValue = 0; // Max value smaller than 200
int MinValue = 0; // Min value bigger than 200
int MaxLocation = 0; // index number of Max value
int MinLocation = 0; // index number of Min value
int SearchValue = 200; // criterion value
char inputFileName[] = "input.txt"; // char array for filename check.
int inputDataArray[100]; // Create Array
char bufferArray[100]; // Create Temp.Array
int DataArrayHandle = 0; // Array Control Variable
// File check.
// Not exist 'input.txt'
if ( ( inputData = fopen( inputFileName, "r" ) ) == NULL )
{
printf("Data Error!! input.txt File does not exist!!\n");
exit(1); // end of program
}
// exist 'input.txt'
else
{
printf("===========================found input.txt File!!!===========================\n");
// read file and insert value to array.
while ( fgets(bufferArray,100,inputData) )
{
inputDataArray[DataArrayHandle] = atoi(bufferArray);
DataArrayHandle++;
}
do
{
// Binary Search Algorithm
ArrayCenter = (ArrayLeft+ArrayRight)/2;
if ( inputDataArray[ArrayCenter] == SearchValue )
{
// if center's value 200, setting Min&Max value and index(location)
MinValue = inputDataArray[ArrayCenter-1];
MinLocation = ArrayCenter-1;
MaxValue = inputDataArray[ArrayCenter+1];
MaxLocation = ArrayCenter+1;
break;
}
else if ( inputDataArray[ArrayCenter] > SearchValue && inputDataArray[ArrayCenter+1] < SearchValue )
{
// if center's value not 200 but similar than 200, setting Min&Max value and index(location)
MinValue = inputDataArray[ArrayCenter];
MinLocation = ArrayCenter;
MaxValue = inputDataArray[ArrayCenter+1];
MaxLocation = ArrayCenter+1;
break;
}
else if ( inputDataArray[ArrayCenter] > SearchValue )
{
// if center's value bigger than 200
ArrayLeft = ArrayCenter + 1;
}
else if ( inputDataArray[ArrayCenter] < SearchValue )
{
// if center's value smaller than 200
ArrayRight = ArrayCenter - 1;
}
} while (ArrayLeft <= ArrayRight);
// Print Answer
printf("Minimum Value Bigger Than '200' ☞ %d in %dth array element. \n",MinValue, MinLocation );
printf("Maximum Value Smaller Than '200' ☞ %d in %dth array element.\n",MaxValue, MaxLocation );
}
// close file pointer
fclose(inputData);
// end of mainFunc.
return 0;
}
댓글
댓글 쓰기