using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
二分查找 条件 数组必须排序好的数组
使用递归进行二分查找 取得数组中间索引的值判断要查找的值
如果大于往前查找反之往后查找
1,从小到大拍好序的数组2,开始索引,结束索引,要查找的值
static int BinarySearch(int[] arr, int low, int high, int key) {
int mid = (low + high) / 2;
if (low > high) return -1;
else {
if (arr[mid] == key) return mid;
else if (arr[mid] > key)
return BinarySearch(arr, low, mid - 1, key);
else {
return BinarySearch(arr,mid + 1,high, key);
}
}
}
static int Search(int[] arr, int key) {
int low = 0;
int length = arr.Length - 1;
int mid = (low + length) / 2;
while (length>=low)
{
if (arr[mid] == key) return mid;
else if (arr[mid] > key)
mid -= 1;
else mid++;
}
return -1;
}
(Fibonacci)斐波拉切数列
Fibonacci数列是按以下顺序排列的数字:
1,1,2,3,5,8,13,21,34,55....规律后一个数加上前一个数等于第三个
int a = 1;
int b = 1;
for (int i = 2; i < 15; i++)
{
b = a + b;
a = b - a;
Console.WriteLine(a);
}
int[] a = new int[10];
a[0] = 1;
a[1] = 1;
for (int i = 2; i < a.Length; i++)
{
a[i] = a[i - 1] + a[i - 2];
}
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
----------插入排序
for (int i = 0; i < array.Length; i++)
{
int t = array[i];
int j = i;
while (j>0&&(array[j-1]>t))
{
array[j] = array[j - 1];
j--;
}
array[j] = t;
}
//数组常见操作
//获取最大值,最小值
//排序(选择排序,冒泡排序)
//折半查找(二分查找)
int[] array = new int[] { 10, 9, 11, 6, 26, 23, 1, 54, 23, };
int temp ;
//选择排序
for (int i = 0; i < array.Length; i++)
{
for (int j = i+1; j < array.Length; j++)
{
if (array[i] < array[j]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for (int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}
Console.WriteLine("--------------------------------------------------------------");
//冒泡排序
int[] Bubble = new int[] { 15, 15, 487, 1512, 12, 20, 0, 4154, 121, 95, 124 ,4854};
for (int i = 0; i < Bubble.Length-1; i++)
{
for (int j = 0; j < Bubble.Length-i-1; j++)
{
if (Bubble[j] > Bubble[j + 1]) {
temp = Bubble[j + 1];
Bubble[j + 1] = Bubble[j];
Bubble[j] = temp;
}
}
}
for (int f = 0; f < Bubble.Length; f++)
{
Console.WriteLine(Bubble[f]);
}
Console.WriteLine("_______________________________________________________________________________");
//折半查找
int min = 0;
int max = Bubble.Length-1;
int mid = (min + max) /2;
while (min<=max)
{
mid = (min + max) / 2;
if (4854 < Bubble[mid])
{
max = mid - 1;
}
else if (4854 > Bubble[mid])
{
min = mid + 1;
}
else {
Console.WriteLine(mid);
break;
}
}
Console.ReadKey();
}
}
}
网友评论