본문 바로가기

전체 글25

[자료구조] 이진 탐색 알고리즘의 재귀적 구현 ◆이진 탐색 알고리즘의 반복 패턴을 정리해보면 1, 탐색 범위의 중앙에 목표 값이 저장되었는지 확인 2. 저장되지 않았다면 탐색 범위를 밤으로 줄여서 다시 탐색 시작 ​ ◆이진 탐색 알고리즘의 탐색 실패가 결정되는 시점 :탐색 범위의 시작위치를 의미하는 first가 탐색 범위의 끝을 의미하는 last보다 커지는 경우 →재귀 함수의 탈출 조건이 된다!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #include int BSearchRecur(int ar[], int first, int last, int target) { int mid; if(first > last) return -1; // -1의 반환은 탐색의 실패. mid = (first + last) / 2; // 탐색 대상의 중앙을 찾.. 2022. 1. 22.
[자료구조] 함수의 재귀적 호출 재귀함수 : 함수 내에서 자기 자신을 다시 호출하는 함수 void Recursive(void){ printf("Recursive call! \n"); Recursive(): } 나도 처음에는 "어떻게 완료되지 않은 함수를 다시 호출하지?" 라고 생각했는데 함수가 호출되면 해당 함수의 복사본을 만들어서 실행하는 구조이기 때문에 ​ Recursive 함수를 실행하는 중간에 다시 Recursive 함수가 호출되면, Recursive 함수의 복사본을 하나 더 만들어서 복사본을 실행한다 ​ 라고 생각하면 된다. ​ 하지만 위의 예제는 Recursive함수에 '재귀의 탈출조건'이 없기 때문에 한번 호출되면 계속 호출되는 문제가 있다. 따라서 탈출의 조건을 추가해보자 #inckude void Recursive(int.. 2022. 1. 22.
[C++] 어서와 C++은 처음이지! 14장 프로그래밍 연습문제 해답 1번 #include #include using namespace std; int main() { try { cout > i; if (i < 0) { throw "오류: 양수를 입력하여야 함\n"; } else { cout 2022. 1. 22.
[C++] 어서와 C++은 처음이지 12장 프로그래밍 연습문제 해답 1번 #include using namespace std; class Shape { int x, y; public: Shape(int x = 0, int y = 0) :x(x), y(y) {} virtual double getArea() = 0; }; class Rect : public Shape { double len, len2; public: Rect(int _x = 0, int _y = 0, int l = 0, int l2 = 0) : Shape(_x, _y), len(l), len2(l2) { } double getArea() { return len * len2; } }; class Triangle : public Shape { double width, height; public: Triangle.. 2022. 1. 22.
[C++] 어서와 C++은 처음이지 11장 프로그래밍 연습문제 해답 1번 #include #include using namespace std; class Point { int x, y; public: Point(int _x = 0, int _y = 0) { x = _x; y = _y; }//생성자 ~Point() { } //접근자 int getX() { return x; } int getY() { return y; } //설정자 void setX(int _x) { x = _x; } void setY(int _y) { y = _y; } }; class ThreeDPoint : public Point { int z; public: ThreeDPoint(int _x = 0, int _y = 0, int _z = 0) : Point(_x, _y){ z = _z; }//생성자 ~.. 2022. 1. 22.