【发布时间】:2019-05-16 13:22:44
【问题描述】:
我有一种方法是“选择排序的改进版本”。但是,代码没有运行为“ temp[x] = 0;”此行给出了超出数组范围的错误。我不想使用 ArrayList。我如何将这条线更改为在数组的范围内?
public static void ImprovedSelectionSort(int[] Array)
{
Stopwatch timer = new Stopwatch();
timer.Start();
int[] temp = new int[Array.Length];
for (int x = 1; x <= Array.Length; x++)
{
//OtherList.Add(0); -- what I want to do
temp[x] = 0;
}
int n = Array.Length;
int i = 0;
while (i < n)
{
int rear = 0;
int curMax = Array[i];
temp[rear] = i;
int j = i + 1;
while (j < n)
{
if (curMax < Array[j])
{
curMax = Array[j];
rear = -1;
}
if (curMax == Array[j])
{
rear = rear + 1;
temp[rear] = j;
}
j++;
}
int front = 0;
int p = Array[temp[front]];
while (front <= rear)
{
int temporary = p;
Array[temp[front]] = Array[i];
Array[i] = temporary;
i++;
front += 1;
}
}
【问题讨论】:
-
for (int x = 1; x <= Array.Length; x++) {temp[x] = 0;}- C# 中的数组从零开始,你可能想要for (int x = 0; x < Array.Length; x++) {temp[x] = 0;}