算法练习

本文介绍了一种用于按特定数值进行分离排序的算法。该算法通过设置高低指针,并使用两个并行循环从数组头部到底部及底部到头部检查无效数字,从而实现高效排序。最坏情况下时间复杂度为O(n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static string GetLastNum(string str)
        {
            if (string.IsNullOrEmpty(str)) throw new ArgumentNullException("参数不能为空");

            string found = string.Empty;
            bool hasFound = false;
            string finalResult = "0";

            foreach (char t in str)
            {
                if (char.IsNumber(t))
                {
                    found += t;
                    hasFound = true;
                }
                else
                {
                    if (!hasFound) continue;

                    finalResult = found;
                    hasFound = false;
                    found = string.Empty;
                }
            }
            return finalResult;
        }


  /// <summary>
        /// NOTICE:
        /// This algorithm is used to do seperate sorting by a certain number.
        /// The thought is:
        /// 1) Set low or high at the top/bottom of your array.
        /// 2) We MUST limit that low is smaller than high, otherwise the loop breaks.
        /// 3) Put two parallel loop from head to bottom/from bottom to head to check whether we have numbers invalid, and then do sorting.
        /// 4) The worse thing is that the number is totally unsorted, or the array is already sorted. This takes "2n" in time, so the time complex is O(n), while the S is S(1)
        /// </summary>
        /// <param name="numbers">
        /// All the numbers to be sorted
        /// </param>
        /// <param name="compareNum">
        /// The seperator number.
        /// </param>
        /// 10, 1000,  400, 4000, -111 
        static void SortByNum(int[] numbers, int compareNum = 1000)
        {
            int low = 0, high = numbers.Length - 1;
            int temp = 0;
            do
            {
                if (numbers[low] < compareNum && numbers[high] >= compareNum)
                {
                    temp = numbers[low];
                    numbers[low] = numbers[high];
                    numbers[high] = temp;
                    low++;
                    high--;
                }
                else if (numbers[low] < compareNum && numbers[high] < compareNum)
                {
                    high--;
                }
                else if (numbers[low] >= compareNum && numbers[high] >= compareNum)
                {
                    low++;
                }
                else
                {
                    low++;
                    high--;
                }

            } while (low < high);
        }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值