排序与查找算法有很多种,我们不必全部记住它,只需记住最快的方法就好了(当然,你也可以用c#自带的方法或者Linq,这不在本文讨论之列)
直接上代码:
/// <summary>
/// 折半查找
/// </summary>
/// <param name="dDataList"></param>
/// <param name="data"></param>
/// <returns></returns>
public static int BinarySearch(List<int> dDataList, int data, int low, int high)
{
int mid = (low + high) / 2;
if (dDataList[mid] == data)
return mid;
if (low > high)
return -1;
if (data < dDataList[mid])
return BinarySearch(dDataList, data, low, mid - 1);
else
return BinarySearch(dDataList, data, mid + 1, high);
}
/// <summary>
/// 快速排序
/// </summary>
/// <param name="dDataList"></param>
/// <param name="low"></param>
/// <param name="high"></param>
public static void QuickSort(ref List<int> dDataList, int low, int high)
{
if (low >= high)
return;
int temp = dDataList[low];//以a[low]为枢纽值
int i = low, j = high;
//一趟快速排序
while (i < j)
{//双向扫描
while (i < j && dDataList[j] >= temp)
j--;
dDataList[i] = dDataList[j];
while (i < j && dDataList[i] <= temp)
i++;
dDataList[j] = dDataList[i];
}
dDataList[i] = temp;//放置枢纽值
//分别对左边、右边排序
QuickSort(ref dDataList, low, i - 1);
QuickSort(ref dDataList, i + 1, high);
}