折半查找类
//折半查找
//____________________________________________________________________________
//____________________________________________________________________________
//___________________________________________________________________________
public int BinarySearch(int[] a, int key, int n)
{
int low = 0;
int high = n - 1;
while (low <= high)//当前区间存在元素时循环
{
int mid = (low + high) / 2;//求查找区间的中间位置
if (a[mid] == key)//查找成功,返回其逻辑序号mid+1
{
return mid + 1;
}
if (a[mid] < key)//继续查找
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
冒泡排序类
//冒泡排序
//____________________________________________________________________________
//____________________________________________________________________________
//___________________________________________________________________________
class MP
{
public int[] mp(int[] list)
{
for (int i = 0; i < list.Length - 1; i++)
{
for (int j = 0; j < list.Length - 1 - i; j++)//一趟中找出最小关键字的元素
{
if (list[j] > list[j + 1])//反序时交换
{
int t = list[j];
list[j] = list[j + 1];
list[j + 1] = t;
}
}
}
return list;
}
窗口设计
代码实现
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Sqlist
{
public partial class zhebanchazhao : Form
{
MP m = new MP();
string[] temp;
int[] list;
public zhebanchazhao()
{
InitializeComponent();
}
//创建顺序表
private void button1_Click(object sender, EventArgs e)
{
string str = textBox1.Text.Trim();
if (str == "")
MessageBox.Show("请输入元素,否则无法进行运算", "信息提示", MessageBoxButtons.OK);
else
{
string[] split = str.Split(new Char[] { ' ', ',', '.', ':' });//视线多种符号分割字符串
temp = textBox1.Text.Split(new[] { ' ', ',', '.', ':', ' ' }, StringSplitOptions.RemoveEmptyEntries);
list = Array.ConvertAll<string, int>(temp, s => int.Parse(s));
label5.Text = "操作提示:成功创建顺序表";
}
}
//排序并输出有序顺序表
private void button2_Click(object sender, EventArgs e)
{
//输出信息
if (textBox1.Text == "")
{
MessageBox.Show("请先输入元素,再进行输出", "信息提示", MessageBoxButtons.OK);
textBox2.Text = "";
}
int[] list1 = m.mp(list);
foreach (int item in list1)
{
textBox2.Text += (item + " ");
}
}
//查找序号
private void button4_Click(object sender, EventArgs e)
{
int key = Convert.ToInt32(textBox4.Text);
textBox5.Text = m.BinarySearch(m.mp(list), key, Convert.ToInt32(list.Length)).ToString();
}
//清空
private void button3_Click(object sender, EventArgs e)
{
//清空顺序表
textBox1.Text = " ";
textBox2.Text = " ";
}
}
}
效果展示
程序下载(包含顺序表、单链表、顺序栈、冒泡排序、折半查找):https://download.csdn.net/download/HAIIAKU/20672183