问题描述
我已经阅读了很多关于对二维数组进行排序的帖子,但我仍然无法掌握它,所以我想知道是否有人可以给我一些建议...
I've read lots of posts about sorting a 2D array but I still can't master it so I was wondering if anyone can offer me some advice...
我有一个列出字母和数量的数组(我正在对一段文本进行频率分析).我已将此数据读入一个矩形数组,需要先按最高频率对其进行排序.到目前为止,这是我的代码:
I have an aray which lists letters and quantity (I'm doing a frequency anaysis on a piece of text). I've read this data into a rectangle array and need to order it by highest frequency first. Here's my code so far:
//create 2D array to contain ascii code and quantities
int[,] letterFrequency = new int[26, 2];
//fill in 2D array with ascaii code and quantities
while (asciiNo <= 90)
{
while ((encryptedText.Length - 1) > counter)
{
if (asciiNo == (int)encryptedText[index])
{
letterCount++;
}
counter++;
index++;
}
letterFrequency[(storeCount), (0)] = (char)(storeCount+66);
letterFrequency[(storeCount), (1)] = letterCount;
storeCount++;
counter=0;
index=0;
letterCount = 0;
asciiNo++;
}
推荐答案
您正在使用 2D 数组来表示 2 个单独的向量 - 符号和计数.相反,使用 2 个单独的数组.Array.Sort 有一个重载,它接受 2 个数组,并对 一个 数组进行排序,但将更改应用于两者,实现您想要的.
You are using a 2D array to represent 2 separate vectors - the symbols and the counts. Instead, use 2 separate arrays. Array.Sort has an overload that takes 2 arrays, and sorts on one array, but applies the changes to both, achieving what you want.
这也将允许您对字符使用 char[] 而不是 int[]:
This would also allow you to use a char[] for the characters rather than int[]:
char[] symbols = ...
int[] counts = ...
...load the data...
Array.Sort(counts, symbols);
// all done!
此时点,计数已排序,并且符号仍将逐个索引与它们相关的计数匹配.
At thispoint, the counts have been ordered, and the symbols will still match index-by-index with the count they relate to.
这篇关于如何在 C# 中对二维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!