【发布时间】:2019-03-31 18:03:37
【问题描述】:
我是编程新手。 C# 是我的第一门编程语言。
我有一个任务,我必须使用数组创建和测试冒泡排序算法和选择排序算法。我想我现在明白这些了。
作业的下一部分我遇到了一些麻烦。
我必须编写一个程序来询问用户一个数字 (n) 并创建 1000 个 n 大小的数组。
因此,如果用户输入 5 作为数字,我的程序必须创建和排序 1000 个长度为 5 的数组。
我必须使用我创建的冒泡排序和选择排序方法。
在我这样做之后,我必须将一个名为 running_time 的变量初始化为 0。我必须创建一个迭代 1000 次的 for 循环,并且在循环体中我必须创建一个数组n 个随机整数。
然后我必须获取时间并将其设置为开始时间。我的教授说要注意排序是在每个数组构建后开始的,所以我应该只对排序过程进行计时。
然后我必须获取时间并将其设置为结束时间。我必须从结束时间中减去开始时间并将结果添加到总时间中。
程序运行后,请注意 1.排序的项目数 2.每个数组的平均运行时间(总时间/1000)
然后我必须使用 500、2500 和 5000 作为数组的大小重复该过程。
这是我创建一个包含 n 个空格并填充随机整数的数组的代码。
//Asks the user for number
Console.WriteLine("Enter a number: ");
n = Convert.ToInt32(Console.ReadLine());
//Creates an array of the length of the user entered number
int[] randArray = new int[n];
//Brings in the random class so we can use it.
Random r = new Random();
Console.WriteLine("This is the array: ");
//For loop that will put in a random number for each spot in the array.
for (int i = 0; i < randArray.Length; i++) {
randArray[i] = r.Next(n);
Console.Write(randArray[i] + " ");
}
Console.WriteLine();
这是我的冒泡排序算法代码:
//Now performing bubble sort algorithm:
for (int j = 0; j <= randArray.Length - 2; j++) {
for (int x = 0; x <= randArray.Length - 2; x++) {
if (randArray[x] > randArray[x + 1]) {
temp = randArray[x + 1];
randArray[x + 1] = randArray[x];
randArray[x] = temp;
}
}
}
//For each loop that will print out the sorted array
foreach (int array in randArray) {
Console.Write(array + " ");
}
Console.WriteLine();
这是我的选择排序算法代码:
//Now performing selection sort algorithm
for (int a = 0; a < randArray1.Length - 1; a++) {
minkey = a;
for (int b = a + 1; b < randArray1.Length; b++) {
if (randArray1[b] < randArray1[minkey]) {
minkey = b;
}
}
tempSS = randArray1[minkey];
randArray1[minkey] = randArray1[a];
randArray1[a] = tempSS;
}
//For loop that will print the array after it is sorted.
Console.WriteLine("This is the array after the selection sort algorithm.");
for (int c = 0; c < randArray1.Length; c++) {
Console.Write(randArray1[c] + " ");
}
Console.WriteLine();
这是非常令人难以抗拒的,因为我是新手,我仍在学习这门语言。
有人可以在开始时指导我如何创建 1000 个不同的数组,其中填充了随机数,然后是其余的。我将不胜感激。谢谢你。
【问题讨论】:
-
var rand = new Random(); var arr = Enumerable.Range(0, 1000).Select(i => rand.Next(1, 1000)).ToArray();
标签: c# arrays algorithm sorting random