一日一プロ

二分探索

using System;
using System.Collections.Generic;

namespace BinarySearch
{
	class MainClass
	{
		public static void Main (string[] args)
		{
			Console.WriteLine ("Target:");
			int target = int.Parse (Console.ReadLine ());
			Console.WriteLine ("List_Num:");
			int N = int.Parse (Console.ReadLine ());
			Console.WriteLine ("List_Data");
			List<int> data = new List<int> ();
			for (int i = 0; i < N; i++) {
				data.Add (int.Parse (Console.ReadLine ()));
			}

			int left = 0;
			int right = N;

			while (right > left) {
				int mid = (left + right) / 2;

				Console.WriteLine ("Left:{0}, Right:{1}, Mid:{2}", left, right, mid);

				if (data [mid] == target) {
					Console.WriteLine ("TRUE");
					break;
				}else if (data[mid] < target) {
					left = mid + 1;
				} else {
					right = mid;
				}
			}
		}
	}
}
広告を非表示にする