选择排序实现

Selection Sort Implementation

我正在研究排序算法。我对选择排序的实现如下:

using System;

namespace Sort
{
    class Program
    {    
        static void SelectionSort(int[] arr)
        {
            int smallestIndex, index, minIndex, temp; 
            for (index = 0; index < arr.Length - 1; index++)
            {
                smallestIndex = index; 
                for (minIndex = index; minIndex < arr.Length; minIndex++)
                {
                    if (arr[minIndex] < arr[smallestIndex])
                        smallestIndex = minIndex;
                    temp = arr[smallestIndex];
                    arr[smallestIndex] = arr[index];
                    arr[index] = temp; 
                }
            }
        }

        static void Main(string[] args)
        {
            int[] myList = {18, 16, 3, 90, 22, 10, 18, 7, 0, 43, 72, 98, 5, 44};
            string unsorted = "";
            string sorted = ""; 
            // First, display the contents of the unsorted list.
            foreach (var item in myList)
            {
                unsorted = unsorted + item.ToString() + " "; 
            }
            Console.WriteLine("- Original list: " + unsorted);
            // Now, sort and display the contents of the list after sorting. 
            SelectionSort(myList); 
            foreach (var item in myList)
            {
                sorted = sorted + item.ToString() + " "; 
            }
            Console.WriteLine("- Sorted list: " + sorted); 
            Console.WriteLine("- List Size " + myList.Length); 
        }
    }
}

这会产生以下输出:

- Original list: 18 16 3 90 22 10 18 7 0 43 72 98 5 44
- Sorted list: 7 3 10 16 18 18 22 43 0 44 5 72 90 98
- List Size 14

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

只需将交换部分从循环中取出即可。

The second for is followed by parentheses and must be restricted.

    static int [] Selectsort(int [] dizi)
      {

              int smallestIndex, index, minIndex, temp; 

        for (index = 0; index < dizi.Length - 1; index++)
        {
            smallestIndex = index;

            for (minIndex = index; minIndex < dizi.Length; minIndex++)
            {
                if (dizi[minIndex] < dizi[smallestIndex])
                {
                    smallestIndex = minIndex;
                }
            }
            temp = dizi[smallestIndex];
                dizi[smallestIndex] = dizi[index];
                dizi[index] = temp; 

        }

        return dizi;
    }
public static class SelectionSort
{
    static int min;
    public static void Sort(int[] data)
    {
        for (int i = 0; i < data.Length; i++)
        {
            for (int j = 0; j < data.Length; j++)
            {
                min = j;
                if (data[i] < data[j])
                    Swap(x: ref data[i], y: ref data[min]);
            }
        }
    }

    private static void Swap(ref int x, ref int y)
    {
        x = x + y;
        y = x - y;
        x = x - y;
    }
}