U E D R , A S I H C RSS

몸짱프로젝트/Binary Search

C version

  • 개발자 : 나휘동

~cpp 
#include <stdio.h>

int * sort(int aArr[]);
void swap(int & aVal1, int & aVal2);
const int SIZE = 10;

int search(const int aArr[], const int aNum, int front, int rear);

void main()
{
	int arr[SIZE] = {1,13,11, 22,6,4,72,11,9,10};
	int * p_arr = sort(arr);
	int result = search(arr, 1, 0, SIZE);
	printf("Position : %d\n", result);
}

int * sort(int aArr[])
{
	for ( int i = 0 ; i < SIZE ; i++)
		for ( int j = 0 ; j < SIZE ; j++)
			if ( aArr[i] < aArr[j] )
				swap(aArr[i], aArr[j]);
	return aArr;
}

void swap(int & aVal1, int & aVal2)
{
	int temp = aVal1;
	aVal1 = aVal2;
	aVal2 = temp;
}

int search(const int aArr[], const int aNum, int front, int rear)
{
	if ( front <= rear )
	{
		int mid = (front + rear)/2;
		if ( aNum == aArr[mid] )
			return mid;
		else if ( aNum > aArr[mid] )
			return search( aArr, aNum, mid + 1, rear );
		else
			return search( aArr, aNum, front, mid - 1);
	}
	return -1;
}

Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:29:28
Processing time 0.0130 sec