我正在学习如何从头开始创建二进制搜索算法的教程.但是我收到错误“使用未分配的局部变量’Pivot’”.我是这门语言的新手,以前只尝试过更简单的语言.
我为缺乏内部文档和使用空白区域而道歉.
这是程序:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Binary_Search_2
- {
- class Program
- {
- static void Main(string[] args)
- {
- int[] arr = new int[10];
- Random rnd = new Random();
- for (int i = 0; i < arr.Length; i++)
- {
- arr[i] = rnd.Next(1,10);
- }
- Array.Sort(arr);
- for (int i = 0; i < arr.Length; i++)
- {
- Console.Write("{0},",arr[i]);
- }
- int Start = 0;
- int End = arr.Length;
- int Center = Start + End / 2;
- int Pivot;
- while (arr[6] > 0)
- {
- while (arr[6] < arr[Center])
- {
- End = Center;
- Center = (End + Start) / 2;
- if (Pivot == arr[Center])
- {
- Console.WriteLine("The Index is {0}",arr[Center]);
- }
- break;
- }
- while (arr[6] > arr[Center])
- {
- Start = Center;
- Center = (End + Start) / 2;
- if (Pivot == arr[Center]) //**This is where the error occurs.**
- {
- Console.WriteLine("The index is {0}",arr[Center]);
- }
- }
- }
- }
- }
- }
我很抱歉,如果这真的很简单,但我没有任何人直接教我,我没有想法.