选择排序实现

Selection Sort Implementation

我不太确定我的实现有什么问题。我该如何解决这个问题?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SelectionSort

{
  class Program
  {

    static void algorithm(int[] to_sort)        
    {
        int bufor;

        for (int i = 0; i < to_sort.Length; i++)
        {
            for (int j = i + 1; j < to_sort.Length; j++)
            {

                if (to_sort[i] >= to_sort[j])     
                {                           
                    bufor = to_sort[i];         
                    to_sort[i] = to_sort[j];
                    to_sort[j] = bufor;
                }
            }
        }
    }

    static void Main(string[] args)
    {

        int[] to_sort = new int[100];   

        Console.WriteLine("");

        for (int i = 1; i < 100; i++)       
        {


            Console.Write(to_sort[i] + " ");    
        }

        Console.WriteLine("");

        algorithm(to_sort);
        Console.WriteLine("\n");
        Console.WriteLine("Sorted list:");
        for (int i = 0; i < 100; i++)        
        {
            Console.Write(to_sort[i] + " ");
        }
        Console.Read();
    }
  }
}

这会产生以下输出:

Original list: 00000000000000000000000000000000000000000000000000000000000
               00000000000000000000000000000000000000000000000000
Sorted list: 000000000000000000000000000000000000000000000000000000000000
              00000000000000000000000000000000000000000000000000

看起来我的数组 (int[] to_sort) 是空的,对吗?我怎样才能得到这个:

Original list: 123456789....100
Sorted list: 123456789...100

也许你来自 C++ 世界,在 C++ 世界中初始化数组并不意味着数组是“cleaned”(碰巧位于分配内存中的数据保持不变) ,但在 C# 中,如果您初始化一个数组,例如:

int[] to_sort = new int[100];

这意味着您构造一个数组,其中 每个元素都设置为 default(T),类型为 T。对于 int,即 0(对于对象,它是 null,等等)。所以你刚刚构造了一个用零填充的数组。

然而,您可以用随机数填充它,例如:

Random rand = new Random();

for(int i = 0; i < to_sort.Length; i++) {
    to_sort[i] = rand.Next(0,1000);
}

编辑

根据您的评论,您想用职位填充它,您可以这样做:

for(int i = 0; i < to_sort.Length; i++) {
    to_sort[i] = i+1;
}

我认为初始化序列号数组的最简单和最短的方法是这样的:

int[] to_sort = Enumerable.Range(1, 100).ToArray();

你所拥有的只是分配数组并用 int 的默认值填充它,即 0:

int[] to_sort = new int[100];