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

C#新手求助:不使用Sort函数实现List<int>升序排序及输入逻辑优化

Hey there! Let's tackle your two C# problems one by one—first fixing that messy input logic, then implementing a manual sort without using the built-in Sort() method.

一、优化输入逻辑 & 修复循环失效问题

Your original code had a redundant while loop that ran only once because you added all 5 elements in one go, making the loop's condition useless. Plus, repeating the input code 5 times was super inefficient. Here's a cleaner, more robust solution:

Optimized Input Code Example

namespace Activity4 { 
    class Worksheet4 { 
        static void Main(string[] args) { 
            List<int> nums = new List<int>();
            const int totalNumbers = 5; // Use a constant to easily adjust input count later

            for (int i = 1; i <= totalNumbers; i++)
            {
                // Dynamically generate proper ordinal labels (1st, 2nd, 3rd...)
                string ordinalSuffix = GetOrdinalSuffix(i);
                Console.Write($"Enter the {i}{ordinalSuffix} number: ");
                
                // Add input validation to avoid crashes from non-numeric entries
                while (!int.TryParse(Console.ReadLine(), out int inputNum))
                {
                    Console.WriteLine("Oops, that's not a valid number. Please try again:");
                }
                
                nums.Add(inputNum);
            }

            // Optional: Print original input for comparison
            Console.WriteLine("\nOriginal numbers:");
            foreach (int num in nums)
            {
                Console.WriteLine(num);
            }
        }

        // Helper method to create correct ordinal suffixes
        static string GetOrdinalSuffix(int number)
        {
            if (number >= 11 && number <= 13)
                return "th";
            
            return number % 10 switch
            {
                1 => "st",
                2 => "nd",
                3 => "rd",
                _ => "th"
            };
        }
    }
}

Key Improvements:

  • Replaced repeated input code with a for loop, making the code easier to maintain (just change totalNumbers to adjust how many inputs you need)
  • Added dynamic ordinal labels so you don't have to hardcode "1st", "2nd", etc.
  • Included input validation with int.TryParse to prevent the program from crashing if the user enters non-numeric text
  • Removed the useless while loop, using the for loop directly to control input count for clearer logic

二、Manual Ascending Sort (No Sort() Method)

For beginners, Bubble Sort is one of the easiest sorting algorithms to understand. It works by repeatedly comparing adjacent elements and swapping them if they're in the wrong order, until the entire list is sorted.

Bubble Sort Implementation (Add This After Input Collection)

// Manual bubble sort for ascending order
int count = nums.Count;
for (int i = 0; i < count - 1; i++)
{
    // Each pass moves the largest unsorted element to the end, so we can skip the last i elements
    for (int j = 0; j < count - i - 1; j++)
    {
        // Swap if current element is larger than the next one
        if (nums[j] > nums[j + 1])
        {
            int temp = nums[j];
            nums[j] = nums[j + 1];
            nums[j + 1] = temp;
        }
    }
}

// Print sorted results
Console.WriteLine("\nSorted numbers (ascending):");
foreach (int num in nums)
{
    Console.WriteLine(num);
}

Bubble Sort Breakdown:

  • The outer loop controls how many passes we make through the list (we need count-1 passes because the last element will sort itself)
  • The inner loop handles comparing adjacent elements and swapping them. We reduce the loop length each time because the largest unsorted element gets "bubbled" to its correct position at the end of the list
  • A temporary variable temp is used to hold one element while we swap positions

Full Integrated Code

namespace Activity4 { 
    class Worksheet4 { 
        static void Main(string[] args) { 
            List<int> nums = new List<int>();
            const int totalNumbers = 5;

            // Collect user input
            for (int i = 1; i <= totalNumbers; i++)
            {
                string ordinalSuffix = GetOrdinalSuffix(i);
                Console.Write($"Enter the {i}{ordinalSuffix} number: ");
                
                while (!int.TryParse(Console.ReadLine(), out int inputNum))
                {
                    Console.WriteLine("Oops, that's not a valid number. Please try again:");
                }
                
                nums.Add(inputNum);
            }

            // Print original numbers
            Console.WriteLine("\nOriginal numbers:");
            foreach (int num in nums)
            {
                Console.WriteLine(num);
            }

            // Manual bubble sort
            int count = nums.Count;
            for (int i = 0; i < count - 1; i++)
            {
                for (int j = 0; j < count - i - 1; j++)
                {
                    if (nums[j] > nums[j + 1])
                    {
                        int temp = nums[j];
                        nums[j] = nums[j + 1];
                        nums[j + 1] = temp;
                    }
                }
            }

            // Print sorted numbers
            Console.WriteLine("\nSorted numbers (ascending):");
            foreach (int num in nums)
            {
                Console.WriteLine(num);
            }
        }

        static string GetOrdinalSuffix(int number)
        {
            if (number >= 11 && number <= 13)
                return "th";
            
            return number % 10 switch
            {
                1 => "st",
                2 => "nd",
                3 => "rd",
                _ => "th"
            };
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 14:17:36