【C#】BinarySearch(), Sort(), and Reverse()方法介绍

1. BinarySearch()
The BinarySearch() method is used to find the index of a specific element in a sorted array. This method performs a binary search, which is an efficient search algorithm that works by repeatedly dividing the search interval in half.
BinarySearch()方法用于查找已排序数组中特定元素的索引。该方法执行二分搜索,这是一种高效的搜索算法,通过重复将搜索间隔分成两半来工作
Key Points:
The array must be sorted for BinarySearch() to work correctly.
The method returns the index of the specified element if it is found.
If the element is not found, the method returns a negative number which is the bitwise complement of the index of the next element that is larger than the specified element.
重点:
数组必须排序,BinarySearch()才能正常工作。
如果找到指定元素,该方法将返回该元素的索引。
如果未找到该元素,则该方法返回一个负数,该负数是下一个大于指定元素的元素的索引的按位补码。

int[] sortedArray = { 1, 3, 5, 7, 9 };  
int index = Array.BinarySearch(sortedArray, 7);  // Returns 3  
index = Array.BinarySearch(sortedArray, 4);  // Returns -4 (not found)

2. Sort()
The Sort() method is used to sort the elements of an array in ascending order. There are also overloads and variations that allow you to sort in descending order, or use a custom comparer.
Sort()方法用于按升序对数组中的元素进行排序。还有一些重载和变体允许您按降序排序,或者使用自定义比较器。
Key Points:
The method modifies the original array (in-place sort).
By default, it sorts elements in ascending order.
重点:
该方法修改原始数组(就地排序)。
默认情况下,它按升序对元素进行排序。

int[] array = { 9, 7, 5, 3, 1 };  
Array.Sort(array);  // Now array is { 1, 3, 5, 7, 9 }
  1. Reverse()
    The Reverse() method is used to reverse the order of the elements in an array
    Reverse()方法用于反转数组中元素的顺序
    Key Points:
    The method modifies the original array (in-place reversal).
    It works on the entire array, but there are overloads to reverse only a portion of the array.
    重点:
    该方法修改原始数组(就地反转)。
    它可以在整个数组上工作,但是有一些重载只能反转数组的一部分
eg1 reverse the order of the elements in an array

int[] array = { 1, 3, 5, 7, 9 };  
Array.Reverse(array);  // Now array is { 9, 7, 5, 3, 1 }

eg 2 reverse only a portion of the array.
int[] array = { 1, 2, 3, 4, 5, 6, 7 };  
  
// Reverse the section of the array from index 2 to index 5 (inclusive)  
Array.Reverse(array, 2, 4);  
  
// Now array is { 1, 2, 6, 5, 4, 3, 7 }

In this example2, the Array.Reverse(array, 2, 4) call reverses the subarray starting at index 2 and with a length of 4 elements (i.e., elements at indices 2, 3, 4, and 5). The rest of the array remains unchanged.
在本例中,为Array。Reverse(array, 2,4)调用反转从索引2开始,长度为4个元素的子数组(即索引2,3,4和5的元素)。数组的其余部分保持不变。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值