我正在为我的课程执行编程任务,因此在C#中遇到了挑战。当我运行它时,它突出显示numbers [position + 1]并给我错误:System.IndexOutOfRangeException:'索引在数组的边界之外。'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
// array of numbers
int[] numbers = { 9, 5, 4, 15, 3, 8, 11, 2 };
int noOfNumbers = 8;
int temp;
while (noOfNumbers > 1) {
foreach(int position in numbers) {
if (numbers[position] > numbers[position+1])
{
temp = numbers[position];
numbers[position] = numbers[position + 1];
numbers[position + 1] = temp;
}
}
noOfNumbers = noOfNumbers + 1;
}
Console.WriteLine(numbers);
}
}
}
这里是伪代码:
BEGIN
Numbers=[9,5,4,15,3,8,11,2]
AmountOfNumbers=8
Temp=0
WHILE AmountOfNumbers>1
FOR each itemPositionInArray in Numbers
IF Numbers[ItemPositionInArray] > Numbers[ItemPositionInArray+1]
Temp=Numbers[ItemPositionInArray]
Numbers[ItemPositionInArray]=Numbers[ItemPositionInArray+1]
Numbers[ItemPositionInArry+1]=Temp
AmountOfNumbers=AmountOfNumbers-1
OUTPUT(Numbers)
END
这里有一个冒泡的例子。
using System;
public class Program
{
public static void Main()
{
// array of numbers
int[] numbers = { 9, 5, 4, 15, 3, 8, 11, 2 };
// declare a boolean.
bool done;
do
{
// when nothing happens, you're done.
done = true;
// create a for-loop to iterate all item-1 (except the last)
for(int position=0;position<numbers.Length-1;position++)
{
// compare the values in the array
if (numbers[position] > numbers[position+1])
{
// swap the values
int temp = numbers[position];
numbers[position] = numbers[position + 1];
numbers[position + 1] = temp;
// if something was swapped, you're not ready.
done = false;
}
}
// loop until done is set.
} while (!done);
Console.WriteLine(string.Join(",", numbers));
}
}