You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

随机数组线性搜索代码故障求助:无法定位错误点

大O表示法线性搜索代码错误排查求助

我正在学习大O表示法(Big O Notation),尝试对随机数组执行线性搜索,但代码出现运行问题,无法定位错误位置。我使用文本编辑器编写C#代码,这是一个简单的算法测试,现附上代码,请求协助排查代码中的错误:

using System;
using System.Collections.Generic;
using System.Data;

namespace TheBigONotations
{
    public class BigONotations
    {
        ///<properties>Class Properties</properties>
        private int[] theArray;
        private int arraySize;
        private int itemsInArray = 0;
        DateTime startTime;
        DateTime endTime;

        public BigONotations(int size)
        {
            arraySize = size;
            theArray = new int[size];
        }
        ///<order>O(1)</order>
        public void addItemToArray(int newItem)
        {
            theArray[itemsInArray++] = newItem;
        }
        ///<order>O(n)</order>
        public void linearSearch(int value)
        {
            bool valueInArray = false;
            string indexsWithValue = "";

            startTime = DateTime.Now;

            for (int i = 0; i < arraySize; i++)
            {
                if (theArray[i] == value)
                {
                    valueInArray = true;
                    indexsWithValue += i + " ";
                }

            }
            Console.WriteLine("Value found: " + valueInArray);

            endTime = DateTime.Now;
            Console.WriteLine("Linear Search took "+(endTime - startTime) );
        }

        ///<order>O(n^2)</order>
        public void BinarySearch()
        {

        }
        ///<order>O(n)</order>

        ///<order>O(n)</order>

        ///<order>O(n)</order>

        public void generateRandomArray()
        {
            Random rnd = new Random();

            for (int i = 0; i < arraySize; i++)
            {
                theArray[i] = (int)(rnd.Next() * 1000) + 10;
            }
            itemInArray = arraySize - 1;
        }

        public static void Main()
        {

            BigONotations algoTest1 = new BigONotations(100000);
            algoTest1.generateRandomArray();

            BigONotations algoTest2 = new BigONotations(200000);
            algoTest2.generateRandomArray();

            BigONotations algoTest3 = new BigONotations(300000);
            algoTest3.generateRandomArray();

            BigONotations algoTest4 = new BigONotations(400000);
            algoTest4.generateRandomArray();

            BigONotations algoTest5 = new BigONotations(500000);
            algoTest5.generateRandomArray();

            algoTest2.linearSearch(20);
            algoTest3.linearSearch(20);
            algoTest4.linearSearch(20);


        }
    }
}

我已在代码中写入相关逻辑,但出现错误却无法精准定位。经初步排查,代码中generateRandomArray方法存在变量名拼写错误,itemInArray应为itemsInArray,这可能是导致运行故障的原因之一。

内容的提问来源于stack exchange,提问作者BlasioGodi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 05:20:28