我正在尝试对包含许多不同数字的文本文件使用冒泡排序。到目前为止,我已经确定了从文本文件中读取数字的部分,但我正在努力处理使用 bubblesort 排列数字的部分。这也是我第一次使用 stackoverflow 所以 yeah
using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
public class Trial
{
public static void Main(string[]args)
{
Stopwatch stopwatch = new Stopwatch();
// point to where our file actually is
string currentDirectory = Directory.GetCurrentDirectory();
string filePath = Path.Combine(currentDirectory, "a2_task1_input1.txt");
Console.WriteLine(filePath); // This line reveals the filepath
LinkedList<int> list = new LinkedList<int>();
// read the file
string fileContents = File.ReadAllText(filePath);
Console.WriteLine(fileContents); // This line reveals the contents of the file
stopwatch.Start(); // Stopwatch begins
// process the contents of the file
string[] numbers = fileContents.Split(new char[] { ' ', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string number in numbers)
{
int value = int.Parse(number); // The int.parse converts these into numbers
list.AddLast(value);
}
// I want to integrate the bottom lines of code into the part above. But instead of the numbers in the array, I want those in the text file
int[] array = { 2, 4, 1, 3, 8, 6, 9, 7, 5 };
BubbleSort(array);
foreach (int number in array)
{
Console.Write(number + " ");
}
/// This is the end bit of the code I want to integrate
stopwatch.Stop();
long elapsedTimeMs = stopwatch.ElapsedMilliseconds;
Console.WriteLine("");
Console.WriteLine("Elapsed time: " + elapsedTimeMs);
}
static void BubbleSort(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// swap operation
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
程序输出未排序的数字集合,以及int[]数组中排序后的数字。我想在 int[] 数组包含文本文件中的数字的地方