C#数组二分查找法
看了一下的二分查找法!就用C#写了一下代码。
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class array
{
public static void Main(string [] args)
{
Data data = new Data(10);
data.add(1);
data.add(32);
data.add(12);
data.add(45);
data.add(24);
data.cancel(12);
data.size();
data.display();
// data.size();
}
}
class Data
{
/// <summary>
/// 用二分法查找数组
/// </summary>
int number;//数组大小;
int[] list;//数组;
int lower;
int upper;
int current;
public Data(int max)
{
list =new int [max];
number = 0;
}
public void add(int o)
{
int i;
for ( i = 0; i < number; i++)
if ((int)list[i] > (int)o) break;
for (int k = number; k>i ; k--)
{
list[k] = list[k-1];
}
list[i] = o;
number++;
}
public Boolean cancel(int o)
{
int i = find(o);
if (i.Equals("0")) return false;
else
{
for (int k = i; k < number; k++)
{
list[k] = list[k + 1];
}
number--;
return true;
}
}
public int find(int o)
{
lower = 0;
upper = number-1;
while (true)
{
current = (lower + upper) / 2;
if (list[current] == o)
return current;
else if (lower > upper)
return 0;
else if (list[current] > (int)o)
{
upper = current - 1;
}
else if (list[current] < (int)o)
{
lower = current + 1;
}
}
//return ;
}
public void size()
{
Console.WriteLine( number);
}
public void display()
{
for (int i = 0; i < number; i++)
{
Console.WriteLine("值:"+list[i]);
}
Console.ReadLine();
}
}
}
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class array
{
public static void Main(string [] args)
{
Data data = new Data(10);
data.add(1);
data.add(32);
data.add(12);
data.add(45);
data.add(24);
data.cancel(12);
data.size();
data.display();
// data.size();
}
}
class Data
{
/// <summary>
/// 用二分法查找数组
/// </summary>
int number;//数组大小;
int[] list;//数组;
int lower;
int upper;
int current;
public Data(int max)
{
list =new int [max];
number = 0;
}
public void add(int o)
{
int i;
for ( i = 0; i < number; i++)
if ((int)list[i] > (int)o) break;
for (int k = number; k>i ; k--)
{
list[k] = list[k-1];
}
list[i] = o;
number++;
}
public Boolean cancel(int o)
{
int i = find(o);
if (i.Equals("0")) return false;
else
{
for (int k = i; k < number; k++)
{
list[k] = list[k + 1];
}
number--;
return true;
}
}
public int find(int o)
{
lower = 0;
upper = number-1;
while (true)
{
current = (lower + upper) / 2;
if (list[current] == o)
return current;
else if (lower > upper)
return 0;
else if (list[current] > (int)o)
{
upper = current - 1;
}
else if (list[current] < (int)o)
{
lower = current + 1;
}
}
//return ;
}
public void size()
{
Console.WriteLine( number);
}
public void display()
{
for (int i = 0; i < number; i++)
{
Console.WriteLine("值:"+list[i]);
}
Console.ReadLine();
}
}
}