1.快速排序

 参考自: https://www.cnblogs.com/yundan/p/4022056.html

namespace 快速排序算法
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入待排序数列以 , 分割");
string _s = Console.ReadLine();
string[] _sArray = _s.Split(",".ToCharArray());
int _nLength = _sArray.Length;
int[] _nArray = new int[_nLength];
for (int i = ; i < _nLength; i++)
{
_nArray[i] = Convert.ToInt32(_sArray[i]);
} var list = _nArray.ToList();
QuickSort(list, , _nLength - ); foreach (var i in list)
{
Console.WriteLine(i.ToString());
}
Console.ReadLine();
} //left为0,right为数组长度减一,即分别为数组中第一个和最后一个数的索引
private static int Division(List<int> list, int left, int right)
{
while (left < right)
{
int num = list[left]; //将首元素作为分割位置
if (num > list[left + ]) //前一位 > 后一位
{
list[left] = list[left + ]; //将两处位置对调
list[left + ] = num;
left++;
}
else
{
int temp = list[right];
list[right] = list[left + ];
list[left + ] = temp;
right--;
}
Console.WriteLine(string.Join(",", list));
}
Console.WriteLine("--------------\n");
return left; //指向的此时枢轴的位置
}
private static void QuickSort(List<int> list, int left, int right)
{
if (left < right)
{
int i = Division(list, left, right);
//对枢轴的左边部分进行排序
QuickSort(list, i + , right);
//对枢轴的右边部分进行排序
QuickSort(list, left, i - );
}
}
}
}

2.二分查找法

namespace 二分查找法
{
class Program
{
// 数组,low=0,high为数组长度减一,key为查找的数字
public static int BinarySearch(int[]arr,int low,int high,int key)
{
int mid = (low + high) / ; //中间数字
if (low > high)
{
return -; //查找不到
}
else
{
if (arr[mid] == key)
{
return mid;
}
else if (arr[mid] > key)
{
return BinarySearch(arr, low, mid - , key);
}
else
{
return BinarySearch(arr, mid + , high, key);
}
}
}
static void Main(string[] args)
{
int[] shuzu = { , , , , ,,,,,,,,,, }; //先排好大小顺序
int high = shuzu.Length - ;
int jieguo = BinarySearch(shuzu, , high, );
Console.WriteLine("查找数字下标:"+jieguo);
Console.WriteLine("数组长度:"+shuzu.Length );
Console.ReadLine();
}
}
}

输出:

C# 快速排序--二分查找法--拉格朗日插值法-LMLPHP

3.拉格朗日插值法

namespace 拉格朗日插值法
{
class Program
{
private static int Cha(int[] shuzhu, int key)
{
int left = ; //数组中起始位置下标
int right = shuzhu.Length - ; //数组最后一位下标
int middle = -;//查找不到
while (left <= right)
{
middle = left + (right - left) * (key - shuzhu[left]) / (shuzhu[right] - shuzhu[left]);
if (key == shuzhu[middle])
{
return middle;
}
else if (key > shuzhu[middle])
{
left = middle + ;
}
else
{
right = middle - ;
}
}
return -;
}
static void Main(string[] args)
{
int[] num = { , , , , , , , , , ,,,};
int a = Cha(num, );//查找数组中数值为4的下标
Console.WriteLine(a);
Console.ReadLine();
}
}
}

输出:

C# 快速排序--二分查找法--拉格朗日插值法-LMLPHP

05-11 18:30