using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BinaryAlgorithm
{
public class Program
{
static void Main(string[] args)
{
//int[] arr = new int[] { 1, 5, 13, 6, 10, 55, 99, 2, 87, 12, 34, 75, 33, 47, 45 };
int[] arr = new int[] { 1};
SelectionSorter.Sort(arr);
Console.WriteLine("Please input target number!");
int target = Convert.ToInt32(Console.ReadLine());
int index = BinaryAlgorithmI.Sort(arr, target);
if (index == -1)
Console.WriteLine("Target number is out of array!");
else
Console.WriteLine("Target number is at " + index);
Console.ReadKey();
}
}
/// <summary>
/// 二分算法
/// </summary>
public class BinaryAlgorithmI
{
public static int Sort(int[] arr, int searchNum)
{
int result = -1;
int low = 0;
int high = arr.Length - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (searchNum == arr[mid])
{
return ++mid;
}
else if (searchNum < arr[mid])
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
return result;
}
}
/// <summary>
/// 冒泡算法
/// </summary>
public class SelectionSorter
{
public static void Sort(int[] arr)
{
int count = arr.Length;
for (int i = 0; i < count - 1; i++)
{
for (int j = i + 1; j < count; j++)
{
if (arr[j] < arr[i])
{
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}
}
}