Created
March 8, 2016 13:47
-
-
Save oyakodon/3f63704336ba1e60fcb1 to your computer and use it in GitHub Desktop.
C++勉強中。今回は、探索プログラム。 / C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define _CRT_SECURE_NO_DEPRECATE | |
#include<iostream> | |
using namespace std; | |
void swap(int &x, int &y) { | |
int temp; | |
temp = x; | |
x = y; | |
y = temp; | |
return; | |
} | |
void sort(int* arr, int n) { | |
for (int i = 0; i < n - 1; i++) { | |
int min = i; | |
for (int j = i; j < n ; j++) { | |
if (arr[min] > arr[j]) { | |
min = j; | |
} | |
} | |
swap(arr[i], arr[min]); | |
} | |
return; | |
} | |
bool search(int target, int* arr, int n) { | |
sort(arr, n); | |
int left = 0, mid = 0, right = n; | |
while (right >= left) { | |
mid = (right + left) / 2; | |
if (arr[mid] == target){ | |
return true; | |
} | |
else if (arr[mid] < target) { | |
left = mid + 1; | |
} | |
else { | |
right = mid - 1; | |
} | |
} | |
return false; | |
} | |
int main() | |
{ | |
int seq[10] = { 0, 4, 6, 5, 8, 2, 3, 9, 7, 1 }; | |
int n = sizeof(seq) / sizeof(int); | |
int target; | |
cout << "Target > "; | |
cin >> target; | |
if (search(target, seq, n)) { | |
cout << "「" << target << "」は配列内に存在します。" << endl; | |
} | |
else { | |
cout << "「" << target << "」は配列内に存在しま[せん]。" << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment