我正在尝试执行简单的插入排序,C#
但我不知道我做错了什么。当我运行我的程序时,我希望它输出一个像这样的窗口:
before sorting
80 60 40 20 10 30 50 70
during sorting
60 80 40 20 10 30 50 70
40 60 80 20 10 30 50 70
20 40 60 80 10 30 50 70
10 20 40 60 80 30 50 70
10 20 30 40 60 80 50 70
10 20 30 40 50 60 80 70
10 20 30 40 50 60 70 80
after sorting
10 20 30 40 50 60 70 80
但它只显示排序后的部分。我可能做错了什么?
这是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
class CArray
{
private int[] arr;
private int upper;
private int numElements;
public CArray(int size)
{
arr = new int[size];
upper = size - 1;
numElements = 0;
}
public void insert(int item)
{
arr[numElements] = item;
numElements++;
}
public void displayElements()
{
for (int i = 0; i <= upper; i++)
Console.Write(arr[i] + " ");
Console.ReadKey();
}
public void clear()
{
for (int i = 0; i <= upper; i++)
arr[i] = 0;
numElements = 0;
}
public void insertionsort() {
int inner, temp;
for (int outer = 1; outer <= upper; outer++) {
temp = arr[outer];
inner = outer;
while (inner > 0 && arr[inner - 1] >= temp) {
arr[inner] = arr[inner-1];
inner -= 1;
}
arr[inner] = temp;
}
}
}
static void Main(string[] args)
{
CArray nums = new CArray(10);
Random rnd = new Random(100);
for (int i = 0; i < 10; i++)
nums.insert((int)(rnd.NextDouble() * 100));
Console.WriteLine("before sorting: ");
nums.displayElements();
Console.WriteLine("during sorting: ");
nums.insertionsort();
Console.WriteLine("after sorting: ");
nums.displayElements();
}
}
}