C#版二分查找(代碼)

本文介绍了一种使用选择排序算法进行数组排序的方法,并通过二分查找算法在已排序数组中搜索目标数值。代码示例展示了如何实现这些算法并进行交互式测试。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace BinaryAlgorithm
{
    public class Program
    {
        static void Main(string[] args)
        {
            //int[] arr = new int[] { 1, 5, 13, 6, 10, 55, 99, 2, 87, 12, 34, 75, 33, 47, 45 };
            int[] arr = new int[] { 1};
            SelectionSorter.Sort(arr);
            Console.WriteLine("Please input target number!");
            int target = Convert.ToInt32(Console.ReadLine());
            int index = BinaryAlgorithmI.Sort(arr, target);
            if (index == -1)
                Console.WriteLine("Target number is out of array!");
            else
                Console.WriteLine("Target number is at " + index);
            Console.ReadKey();
        }
    }


    /// <summary>
    /// 二分算法
    /// </summary>
    public class BinaryAlgorithmI
    {
        public static int Sort(int[] arr, int searchNum)
        {
            int result = -1;
            int low = 0;
            int high = arr.Length - 1;
            while (low <= high)
            {
                int mid = (low + high) / 2;
                if (searchNum == arr[mid])
                {
                    return ++mid;
                }
                else if (searchNum < arr[mid])
                {
                    high = mid - 1;
                }
                else
                {
                    low = mid + 1;
                }
            }
            return result;
        }
    }


    /// <summary>
    /// 冒泡算法
    /// </summary>
    public class SelectionSorter
    {
        public static void Sort(int[] arr)
        {
            int count = arr.Length;
            for (int i = 0; i < count - 1; i++)
            {
                for (int j = i + 1; j < count; j++)
                {
                    if (arr[j] < arr[i])
                    {
                        int temp = arr[j];
                        arr[j] = arr[i];
                        arr[i] = temp;
                    }
                }
            }
        }
    }
}

转载于:https://my.oschina.net/gaowch/blog/122372

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值