如何使用嵌套的for循环对数组的元素进行排序? [英] How to sort elements of an array using nested for-loops?
问题描述
我正在接受编程方面的挑战,很难解决这个问题.这可能是由于时间和我目前的困倦所致,但我想在睡觉前完成这项工作.
I'm taking on a programming challenge for practice and I'm having trouble figuring this one out. It might be due to the time and my current sleepiness, but I want to get this done before bed.
我想按升序对数组中每个元素的值进行排序.诀窍是不使用sort()方法.这是我到目前为止的内容:
I want to sort the values of each element of an array in ascending order. The trick is not to use a sort() method. Here is what I have so far:
for (int i = 0; i < freq_array.Length; i++)
{
for (int n = 1; n < i; n++)
{
if (freq_array[n] < freq_array[i])
freq_array[i] = freq_array[n];
}
}
for (int x = 0; x < freq_array.Length; x++)
{
lblOutDigits.Text = "";
lblOutDigits.Text += freq_array[x];
}
测试时,标签上只有一个"0".freq_array的作用是保持单击某些按钮的频率.因此,如果我单击Button3 5次,然后单击Button7 3次,将它们按顺序排列,即使我以随机顺序单击3和7,也应该会看到33333777.
When testing it out, I just get a '0' in the label. What the freq_array does is hold the frequency of how often certain buttons are clicked. So if I click Button3 5 times, then Button7 3 times, putting them in order I should see 33333777 - even if I clicked 3 and 7 in a random order.
推荐答案
您需要交换值
int temp;
for (int i = 0; i < freq_array.Length; i++)
{
for (int n = 1; n < i; n++)
{
if (freq_array[n] < freq_array[i]){
temp = freq_array[i];
freq_array[i] = freq_array[n];
freq_array[n] = temp;
}
}
}
这篇关于如何使用嵌套的for循环对数组的元素进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!