C#对int数组排序
时间: 2023-07-20 14:09:31 浏览: 65
可以使用C#的Array类的Sort方法对int数组进行排序。示例代码如下:
```csharp
int[] arr = {5, 2, 9, 1, 8, 3};
Array.Sort(arr);
```
在上述示例中,我们首先定义了一个包含6个元素的int数组arr,并初始化了其值。然后,我们使用Array类的Sort方法对数组进行排序。排序完成后,数组arr的元素顺序会变为1、2、3、5、8、9。
相关问题
用C#写一个程序,把int数组排序并输出原始下标
以下是一个用C#实现的基于冒泡排序的程序,可以将一个int数组进行排序,并输出原始下标:
```csharp
using System;
class Program {
static void Main(string[] args) {
// 定义一个int数组
int[] arr = { 9, 4, 7, 3, 1, 5, 8, 2, 6 };
// 定义一个int数组来存储原始下标
int[] index = new int[arr.Length];
for (int i = 0; i < index.Length; i++) {
index[i] = i;
}
// 冒泡排序
for (int i = 0; i < arr.Length - 1; i++) {
for (int j = 0; j < arr.Length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// 交换数组元素
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
// 交换原始下标
temp = index[j];
index[j] = index[j + 1];
index[j + 1] = temp;
}
}
}
// 输出排序后的数组和原始下标
Console.WriteLine("原始数组:");
for (int i = 0; i < arr.Length; i++) {
Console.Write(arr[i] + " ");
}
Console.WriteLine();
Console.WriteLine("原始下标:");
for (int i = 0; i < index.Length; i++) {
Console.Write(index[i] + " ");
}
Console.WriteLine();
}
}
```
以上代码中,先定义一个int数组和一个同样长度的int数组index来存储原始下标,然后使用冒泡排序对原数组进行排序,并且每次交换数组元素时,也同时交换原始下标数组的元素。最后输出排序后的数组和原始下标即可。
C#List数组冒泡排序
以下是 C# 中使用冒泡排序算法对 List 数组进行排序的示例代码:
```csharp
int[] numbers = new int[] { 4, 2, 8, 3, 1, 9, 5, 7, 6 };
for (int i = 0; i < numbers.Length - 1; i++)
{
for (int j = 0; j < numbers.Length - i - 1; j++)
{
if (numbers[j] > numbers[j + 1])
{
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
foreach (int number in numbers)
{
Console.Write(number + " ");
}
```
在这个示例中,我们创建了一个包含整数的数组,然后使用嵌套的 for 循环遍历数组中的元素,比较相邻的两个元素的大小关系,如果前一个元素大于后一个元素,则交换它们的位置。这样,每一轮循环都会将数组中最大的元素移动到末尾。最后,我们使用 foreach 循环输出已排序的数组。
相关推荐
![](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)