排序方法封装

数据准备“:
const links = [
{
“sort”: 0,
“model_id”: “ew_sellerinfo_filepath”,
“collection_name”: “ewta_resource_data_ew_sellerinfo_filepath”
},
{
“sort”: 1,
“model_id”: “ew_collect_java_process”,
“collection_name”: “ewta_resource_data_ew_collect_java_process”
},
{
“sort”: 2,
“model_id”: “ew_sellerinfo_filetype”,
“collection_name”: “ewta_resource_data_ew_sellerinfo_filepath”
}
]

function handleSort(index, type) {
    if (type == 'up') {
      if (index == 0) return message.error('已经是第一个了')
      // 与前一个元素交换
      let temp = links[index].sort;
      links[index].sort = links[index - 1].sort;
      links[index - 1].sort = temp;
      // 重新排序并更新显示
      links.sort((a, b) => a.sort - b.sort);
      setLinks([...links])
    } else {
      if (index == links.length - 1) return message.error('已经是最后一个了')
      // 与下一个元素交换
      let temp = links[index].sort;
      links[index].sort = links[index + 1].sort;
      links[index + 1].sort = temp;
      // 重新排序并更新显示
      links.sort((a, b) => a.sort - b.sort)
      setLinks([...links])
    }
  }
### C# 中封装排序方法 在 C# 编程中,为了提高代码的可重用性和模块化程度,可以将排序逻辑封装在一个独立的方法内。下面展示了一个通用的 `BubbleSort` 方法封装方式[^2]。 #### 定义泛型类和静态方法 创建一个名为 `SortingUtility` 的工具类,在其中定义一个公共静态方法 `BubbleSort<T>` 来处理不同类型的数组: ```csharp using System; namespace SortingExample { /// <summary> /// 提供各种排序算法实现的帮助器类。 /// </summary> public static class SortingUtility { /// <summary> /// 对指定的一维数组应用冒泡排序算法。 /// </summary> /// <typeparam name="T">数组元素的数据类型。</typeparam> /// <param name="array">待排序的一维数组。</param> public static void BubbleSort<T>(this T[] array) where T : IComparable<T> { bool swapped; do { swapped = false; for (int i = 0; i < array.Length - 1; ++i) { if (array[i].CompareTo(array[i + 1]) > 0) { // Swap elements. T temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; swapped = true; } } } while (swapped); } } } ``` 此版本不仅支持整数类型的数组,还能够接受实现了 `IComparable<T>` 接口的各种数据结构作为参数,使得函数更加灵活多变[^3]。 #### 使用扩展方法简化调用语法 上述例子中使用了 C# 扩展方法特性 (`this`) ,这允许开发者像对待对象本身一样直接调用静态成员,增强了代码的简洁度和易读性。 #### 测试封装后的排序功能 最后编写一段测试代码验证新加入的功能是否正常工作: ```csharp class Program { static void Main() { int[] numbers = { 6, 5, 8, 7, 1, 2, 3, 5 }; Console.WriteLine("原始序列:"); PrintArray(numbers); // 调用我们刚刚封装好的冒泡排序方法 numbers.BubbleSort(); Console.WriteLine("\n已排序序列:"); PrintArray(numbers); Console.ReadKey(); } private static void PrintArray(int[] arr) { foreach (var item in arr) { Console.Write(item.ToString() + " "); } } } ``` 这段程序先打印未经过任何操作前的初始状态,接着调用了自定义的 `BubbleSort()` 函数完成升序排列的任务,并再次显示最终的结果给用户查看。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值