c# - 插入排序算法c#

标签 c# algorithm sorting

我正在尝试在我的一个程序中实现插入排序。我一直试图创建的是一个排序程序(按升序或降序排列)但是我尝试过快速排序和合并排序等算法,我对 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/

相关文章:

python - 如何使用 map 或 reduce 函数在 Python 中压缩列表?

java - 更改 MALLET 中主题分发文件中的列顺序

sorting - 如何在Rust中按降序对Vector进行排序?

c# - 当我创建集合时,Ninject inject 向集合中添加一个元素

c# - 依赖注入(inject)组合根和装饰器模式

C#引用麻烦

algorithm - 需要图论名称/算法帮助

c++ - 如何为 std::sort() 编写用户定义的比较

c# - 控制文档中未给出串行命令的电机

c# - 将对象设置为 null 有什么作用?