c#写出一个选择排序法,然后调用此方法对数组
时间: 2023-12-20 13:06:36 浏览: 41
好的,以下是C#代码实现选择排序法:
```csharp
public static void SelectionSort(int[] arr)
{
int n = arr.Length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n - 1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[min_idx])
{
min_idx = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
```
调用方法:
```csharp
int[] arr = {64, 25, 12, 22, 11};
SelectionSort(arr);
```
调用后,`arr` 数组将会被排序。
相关问题
c#写出一个选择排序的方法然后调用此方法对数组Arr2
好的,以下是一个使用 C# 实现的选择排序方法:
```csharp
static void SelectionSort(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
{
int minIndex = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
```
然后,你可以像下面这样调用此方法对数组 `arr2` 进行排序:
```csharp
int[] arr2 = { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5 };
SelectionSort(arr2);
```
这将会对 `arr2` 进行选择排序,使得数组元素按升序排列。
写一个数组的冒泡排序 c#
以下是C语言实现数组的冒泡排序的代码:
```c
#include <stdio.h>
void bubbleSort(int arr[], int len) {
int i, j, temp;
for (i = 0; i < len - 1; i++) {
for (j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {5, 3, 8, 6, 4};
int len = sizeof(arr) / sizeof(arr[0]);
int i;
printf("排序前的数组:\n");
for (i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
bubbleSort(arr, len);
printf("排序后的数组:\n");
for (i = 0; i < len; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
运行结果:
```
排序前的数组:
5 3 8 6 4
排序后的数组:
3 4 5 6 8
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)