【发布时间】:2017-01-24 09:55:07
【问题描述】:
这是一个数据结构和算法类。我们刚刚开始使用冒泡排序。指令是生成随机的、唯一的整数,并使用讲座的排序技术对它们进行排序。还需要添加不同的排序技术。
为了生成随机数列表,我生成了一个列表,然后使用 Fisher-yates 算法对列表进行了洗牌。所以我有我选择的任何大小的独特排序列表。
我卡住了,因为在生成随机列表后,我在访问列表以通过 BubbleSort 运行它时遇到问题。
有什么办法可以做到吗?
class Algorithms
{
static void Main(string[] args)
{
string response = "";
//Main Console Menu
while (response != "exit")
{
Console.WriteLine("Type help for list of commands");
response = Console.ReadLine();
//List<int> toSort = new List<int>();
if (response.StartsWith("exit"))
{
Environment.Exit(0);
}
else if (response.ToLower().StartsWith("help"))
{
Help(response);
}
else if (response.ToLower().StartsWith("generate"))
{
// Shuffle(Generate(response));
// have been using the line above but adding next line for
//an idea of my problem
List<int> toSort = Shuffle(Generate(response));
}
else if (response.ToLower().StartsWith("bubble"))
{
//This doesn't work and I'm trying to figure out how it can
BubbleSort(toSort);
}
}
}
//Displays help information
public static void Help(string input)
{
Console.WriteLine("\ngenerate <integer> -- Generates a data set of intended amount of integers\n"+
"algorithm <algorithm type> -- Choose which algorithm to sort data\nexit -- exit application\n" );
}
//Generates List of integers from 0 to number choosen by user
public static List<int> Generate(string size)
{
int cutString = size.Length - 9;
string sizeSubset = size.Substring(9, cutString);
List<int> numGen = new List<int>();
int dataSetSize = Convert.ToInt32(sizeSubset);
for(int i = 0; i <= dataSetSize; i++)
{
numGen.Add(i);
// Console.WriteLine(numGen[i]);
}
return numGen;
}
//Use Fisher-Yates algorithm to shuffle the list.
static Random randomize = new Random();
public static List<int> Shuffle(List<int>makeRandom)
{
List<int> shuffled = new List<int>();
int n = makeRandom.Count;
while (n > 1)
{
n--;
int k = randomize.Next(n + 1);
int value = makeRandom[k];
makeRandom[k] = makeRandom[n];
makeRandom[n] = value;
shuffled.Add(value);
Console.WriteLine(value);
}
return shuffled;
}
public static void BubbleSort(List<int>input)
{
for(int i = 0; i <= input.Count; i++)
{
for (int j = 0; j <= (input.Count - 1); j++)
{
if (input[j] > input[j + 1])
{
int temp = input[j];
input[j] = input[j + 1];
input[j + 1] = temp;
Console.WriteLine("hello");
}
}
}
}
}
}
【问题讨论】:
-
嗯,是的,您已经生成了列表 - 但您还没有在任何地方存储对它的引用...考虑在
Main中有一个局部变量存储对列表的引用。 -
我将如何在 C# 中做到这一点?这就是我一直在做的事情,但还没有真正找到任何答案。
-
好吧,我已经给了你一个提示:你的
Main方法中需要一个局部变量。但是您需要确保该变量在"bubble"情况下仍在范围内,因此您需要在while循环之外声明它... -
谢谢,不太明白你的意思。我读到它是最初想到的指针。不过感谢您的帮助!