C#程序在2D数组中找到第K个最小的元素
声明一个2D数组-
int[] a = new int[] {
65,
45,
32,
97,
23,
75,
59
};假设您想要第K个最小整数,即第5个最小整数。首先对数组进行排序-
Array.Sort(a);
获取第五个最小元素-
a[k - 1];
让我们看完整的代码-
示例
using System;
using System.IO;
using System.CodeDom.Compiler;
namespace Program {
class Demo {
static void Main(string[] args) {
int[] a = new int[] {
65,
45,
32,
97,
23,
75,
59
};
//第k个最小元素
int k = 5;
Array.Sort(a);
Console.WriteLine("Sorted Array...");
for (int i = 0; i < a.Length; i++) {
Console.WriteLine(a[i]);
}
Console.Write("The " + k + "th smallest element = ");
Console.WriteLine(a[k - 1]);
}
}
}