c#编写一个函数,实现冒泡排序算法,并捕获下标越界异常
时间: 2023-06-12 14:07:41 浏览: 73
以下是一个示例的 C# 冒泡排序算法实现,并包含捕获下标越界异常的代码:
```csharp
public static void BubbleSort(int[] arr)
{
try
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("下标越界异常:{0}", e.Message);
}
}
```
该函数接受一个整型数组作为参数,并对其进行冒泡排序。在循环过程中,如果出现下标越界异常,程序会捕获该异常并打印异常信息。
相关问题
用C#写一个冒泡排序算法
下面是使用 C# 编写冒泡排序算法的示例代码:
```csharp
static void BubbleSort(int[] arr)
{
int n = arr.Length;
// 外层循环控制排序的轮数
for (int i = 0; i < n - 1; i++)
{
// 内层循环控制每轮排序的次数
for (int j = 0; j < n - i - 1; j++)
{
// 如果相邻的两个元素顺序错误,则交换它们的位置
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
在这个实现中,我们使用了两层循环来完成排序。外层循环控制排序的轮数,内层循环控制每轮排序的次数。在内层循环中,我们比较相邻的两个元素,如果它们的顺序错误,则交换它们的位置。最终,经过多轮排序,数组中的元素就会按照从小到大的顺序排列。
用c#语言写一个冒泡排序算法
以下是使用 C# 编写的冒泡排序算法:
```
public static void BubbleSort(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
使用方法:
```
int[] arr = { 5, 2, 1, 6, 3 };
BubbleSort(arr);
foreach (int i in arr)
{
Console.Write(i + " ");
}
```
输出结果为:`1 2 3 5 6`。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)