选择排序错误:错误的输出;重复项未排序

时间:2019-04-18 12:01:14

标签: c# sorting selection

我的排序算法给出了错误的结果。我已经尝试识别错误,但是我不确定为什么选择排序不起作用。 在哪里修复输出中的错误? 我的输出是 1个 4 5 6 7 3 7 9 10 因此,在7s之间的3不被排序。

static void Main(string[] args)
    {
        int[] Array = { 1, 7, 6, 5, 4, 3, 7, 9, 10 };
        Console.WriteLine("Array before sorting: ");
        for (int i = 0; i <= Array.Length-1 ; i++)
        {
            Console.WriteLine(Array[i] + " " );

        }

        SelectionSort(Array);
        Console.ReadLine();
    }

    public static void SelectionSort(int[] Array) // ascending order
    {
        int min;
        for (int i = 0; i <= Array.Length-1 ; i++) // go through the list
        {
            min = i; // minimum equals the current position in list
            for (int j = i+1; j < Array.Length; j++)
            {
                if (Array[j] < Array[min])
                    min = j; // min equals smallest in list j
                swap(Array, i, min); // swap current position in list i and the smallest position in list j
            }
        }
        Console.WriteLine("Array after selection sort: "); 
        for (int i = 0; i < Array.Length; i++) // display the sorted list
        {
            Console.WriteLine(Array[i] + " ");
        }
    }

    public static void swap(int[] Array,int x, int y)
    {
        int temp = Array[x];
        Array[x] = Array[y];
        Array[y] = temp;
    }

} }

1 个答案:

答案 0 :(得分:2)

static void Main(string[] args)
{
    int[] Array = { 1, 7, 6, 5, 4, 3, 7, 9, 10 };
    Console.WriteLine("Array before sorting: ");
    for (int i = 0; i <= Array.Length-1 ; i++)
    {
        Console.WriteLine(Array[i] + " " );

    }

    SelectionSort(Array);
    Console.ReadLine();
}

public static void SelectionSort(int[] Array) // ascending order
{
    int min;
    for (int i = 0; i <= Array.Length-1 ; i++) // go through the list
    {
        min = i; // minimum equals the current position in list
        for (int j = i+1; j < Array.Length; j++)
        {
            if (Array[j] < Array[min])
                min = j; // min equals smallest in list j
        }
        swap(Array, i, min); // swap current position in list i and the smallest position in list j
    }
    Console.WriteLine("Array after selection sort: "); 
    for (int i = 0; i < Array.Length; i++) // display the sorted list
    {
        Console.WriteLine(Array[i] + " ");
    }
}

public static void swap(int[] Array,int x, int y)
{
    int temp = Array[x];
    Array[x] = Array[y];
    Array[y] = temp;
}
  

交换应该在内部for循环之外。首先,您要找到最小的数字,然后将其与当前元素交换。在您的代码中,它每次变小时都会交换。