鱼C论坛

 找回密码
 立即注册
查看: 3171|回复: 1

运行这个C#写的二分法查找导致栈溢出了

[复制链接]
发表于 2017-10-10 21:03:33 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;

  6. namespace task4
  7. {
  8.     class Program
  9.     {//二分法递归
  10.         List<int> l = new List<int>();
  11.       
  12.         public int BinarySearch(List<int> l,int start,int end,int x)
  13.         {  
  14.             if (start <= end)
  15.             {
  16.                 if (l.Count == 0)
  17.                     return -1;
  18.                 int mid = l.Count / 2;
  19.                 if (l[mid] == x)
  20.                     return mid;
  21.                 else if (x < l[mid])
  22.                     return BinarySearch(l, start, mid - 1, x);
  23.                 else
  24.                 {
  25.                     return BinarySearch(l, mid + 1, end, x);
  26.                 }
  27.             }
  28.             return -1;
  29.            
  30.                
  31.         }
  32.       
  33.         static void Main(string[] args)
  34.         {
  35.             Program pro = new Program();
  36.             int[] sortedData = { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
  37.             for (int i = 0; i < sortedData.Length; i++)
  38.             {
  39.                 pro.l.Add(sortedData[i]);
  40.             }

  41.             int length = pro.l.Count();
  42.             int key = 5;
  43.                 int value =pro.BinarySearch(pro.l, 0, length - 1, key);
  44.                 Console.WriteLine("found in pos"+value);
  45.            
  46.         }
  47.     }
  48. }
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-10-11 14:17:21 | 显示全部楼层
单步调试下就能知道错误在哪
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 04:56

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表