Tìm kiếm mảng


Bài tập 1: Sử dụng thuật toán tìm kiếm tuần tự (sequential search), viết chương trình C# để tìm kiếm một phần tử của mảng 10 phần tử.

Giải pháp:


class Program
{
    static void Main(string[] args)
    {
      int[] arr = new int[10] { 23, 2, 3, 34, 6,1,24,45,78,8}; //tập dữ liệu
      int pos,target;
      Console.Write("Nhập vào giá trị cần tìm");
      target = int.Parse(Console.ReadLine());
      pos = seqsearch(arr, target, 10);
      if (pos != -1)
        Console.WriteLine("Giá trị được tìm thấy tại vị trí:{0}", pos);
      else
        Console.WriteLine("Giá trị không tìm thấy trong danh sách.\n");
      Console.ReadLine();
    }
    ///Thuật toán tìm tuần tự
    static int seqsearch(int[] dataset, int target, int n)
    {
      int found = 0;
      int i;
      int pos = -1;
      for (i = 0; i < n && found != 1; i++)
        if (target == dataset[i]) 
        { 
            pos = i; 
            found = 1; 
        }
       return pos;
    }
}

Bài tập 2: Chỉnh sửa code C# ở bài tập 1 để thực hiện tìm kiếm một phần tử của mảng sử dụng thuật toán tìm kiếm nhị phân.

Gải pháp:


class Program
{
    static void Main(string[] args)
    {
        int[] arr = new int[10] { 23, 2, 3, 34, 6, 1, 24, 45, 78, 8 }; //Tập dữ liệu chưa sắp xếp
        int pos, target;
        Console.Write("Nhập giá trị cần tìm:");
        target = int.Parse(Console.ReadLine());
        pos = binsearch(arr, 23, 10);
        if (pos != -1)
        Console.WriteLine("Giá trị được tìm thấy tại vị trí:{0}", pos);
        else
        Console.WriteLine("Giá trị cần tìm không tìm có trong danh sách.\n");
        Console.ReadLine();
    }
    ///Thuật toán tìm kiếm nhị phân
    static int binsearch(int[] dataset,int target, int l,int u){
        insertsort(dataset,dataset.Length);//Chắc chắn danh sách đẵ sắp xếp
        while(u>=l){  
            int mid=(l+u)/2;  
            if(target==dataset[mid]) return mid;  
            else if(target>dataset[mid]) 
                l=mid+1;  
            else if(target= 0 && inserted != 1; )
            {
                if (pick_item < dataset[j])
                {
                    dataset[j + 1] = dataset[j];
                    j--;
                    dataset[j + 1] = pick_item;
                }
                else 
                    inserted = 1;
            }
        }
    }
}

Có thể bạn sẽ thích…

Trả lời

EnglishVietnamese