我正在尝试在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();
}
}
}
答案 0 :(得分:3)
您的insertionSort()
功能不会向显示屏输出任何内容。
答案 1 :(得分:2)
如何在insertionsort()...?
中的某处调用displayElements()答案 2 :(得分:2)
这对我有用......
public void insertionsort() {
int inner, temp;
for (int outer = 1; outer <= upper; outer++) {
displayElements();
Console.WriteLine();
temp = arr[outer];
inner = outer;
while (inner > 0 && arr[inner - 1] >= temp) {
arr[inner] = arr[inner-1];
inner -= 1;
}
arr[inner] = temp;
}
这是我在insertort()方法中添加两行时得到的输出......
分拣前:
96 15 66 90 35 94 71 61 34 14在分拣过程中:
96 15 66 90 35 94 71 61 34 14
15 96 66 90 35 94 71 61 34 14
15 66 96 90 35 94 71 61 34 14
15 66 90 96 35 94 71 61 34 14
15 35 66 90 96 94 71 61 34 14
15 35 66 90 94 96 71 61 34 14
15 35 66 71 90 94 96 61 34 14
15 35 61 66 71 90 94 96 34 14
15 34 35 61 66 71 90 94 96 14分类后:
14 15 34 35 61 66 71 90 94 96
答案 3 :(得分:-1)
使用系统;
namespace InsertionSort
{
class Program
{
static void Main(string[] args)
{
int[] num = { 90, 110, 80, 30, 10, 20 };
for (int i = 1; i < num.Length; i++)
{
int tmp = num[i];
for (int j = i - 1; j >= 0; j--)
{
int tmpIndex = j + 1;
if (tmp < num[j])
{
num[tmpIndex] = num[j];
num[j] = tmp;
}
}
}
//Write the sorted list numbers
for (int i = 0; i < num.Length; i++)
{
Console.WriteLine(i);
} }
}
}