我正在尝试在我的一个程序中实现插入排序。我一直试图创建的是一个排序程序(按升序或降序排列)但是我尝试过快速排序和合并排序等算法,我对 c# 和编码真的很陌生。我在这里面临的问题是我的文件既包含一串代码,也包含一个 double /整数(例如:75.350、74.430、星期四、星期五),因为该算法是为整数设计的。请问有办法转换吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
StreamReader sh1Open = new StreamReader("c:..\\Files\\SH1_Open.txt");
string Sh1OpenString = sh1Open.ReadToEnd();
int[] x = { Convert.ToInt32(Sh1OpenString) };
int j;
int temp;
for (int i = 1; i < x.Length; i++)
{
j = i - 1;
while (j >= 0 && x[j]>x[j+1])
{
temp = x[j];
x[j] = x[j + 1];
x[j + 1] = temp;
j = j - 1;
}
}
for (int i = 0; i < x.Length; i++)
{
Console.WriteLine(x[i]);
}
Console.ReadKey();
}
}
}
最佳答案
最好的方法可能是使用带有 IComparable 约束的泛型方法。
T[] InsertionSort(T[] x) where T : IComparable<T>
{
for (int i = 0; i < x.Length-1; i++)
{
int j = i+1;
while (j>0)
{
if (x[j-1].CompareTo(x[j]) > 1)
{
T temp = x[j-1];
x[j - 1] = x[j];
x[j] = temp;
}
j--;
}
}
return x;
}
或使用来自 http://www.codecodex.com/wiki/Insertion_sort 的算法
static void InsertSort(IComparable[] array)
{
int i, j;
for (i = 1; i < array.Length; i++)
{
IComparable value = array[i];
j = i - 1;
while ((j >= 0) && (array[j].CompareTo(value) > 0))
{
array[j + 1] = array[j];
j=j-1;
}
array[j + 1] = value;
}
}
此外,这一行中可能存在错误:
int[] x = { Convert.ToInt32(Sh1OpenString) };
因为您正试图将整个文件转换为一个整数。
关于c# - 插入排序算法c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29576228/