选择排序只传递一次

时间:2015-03-17 12:02:40

标签: sorting selection

您正在尝试创建一个选择排序,但它似乎只能通过一次 第一个调试显示这个 3,2,10,9,5,这是正确的 然后第二个调试显示这个 2,0,0,0,0 最后一个显示这个 3,0,10,9,5,

正如你所看到的那样,它似乎只是循环一次,而不是我告诉它的4次我做错了什么?

int[] List = new int[] {3, 2, 10, 9, 5};//List 
    int[] ListB = new int[] {0, 0, 0, 0, 0};//ListB

    Debug.Log(List[0] + ","+List[1] + ","+List[2] + ","+List[3] + ","+List[4] + ",");
    int minimum,temp;//2 new ints

    for (int outer = 0; outer <  List.Length-1; outer++)//Loop for 0 to number of ints in list -1
    {
        minimum = outer;//set minimum to outer

        for (int inner = 0; inner <  List.Length; inner++)//loop for how many ints are in the list
        {
            if (List[inner] < List[minimum])// if list inner < list minimum 
            {
                minimum = inner;//set minimum to inner
            }                                          
        }
        ListB[outer] = List[minimum];//listb outer = list minimum
        List[minimum] = 0;//set the list minimum to a dummy value 
    }
    Debug.Log(ListB[0] + ","+ListB[1] + ","+ListB[2] + ","+ListB[3] + ","+ListB[4]);
    Debug.Log(List[0] + ","+List[1] + ","+List[2] + ","+List[3] + ","+List[4] + ",");

1 个答案:

答案 0 :(得分:1)

当您将列表[minimum]设置为0时,下次循环执行时将找到0作为最小值 你需要注意另一件事,第一个循环应该在list.length完成 这是真正的代码

int[] List = new int[] { 3, 2, 10, 9, 5 };//List 
        int[] ListB = new int[] { 0, 0, 0, 0, 0 };//ListB

        Debug.log(List[0] + "," + List[1] + "," + List[2] + "," + List[3] + "," + List[4] + ",");
        int minimum, temp;//2 new ints

        for (int outer = 0; outer < List.Length ; outer++)//Loop for 0 to number of ints in list -1
        {
            minimum = outer;//set minimum to outer

            for (int inner = 0; inner < List.Length; inner++)//loop for how many ints are in the list
            {
                if (List[inner] < List[minimum])// if list inner < list minimum 
                {
                    minimum = inner;//set minimum to inner
                }
            }
            ListB[outer] = List[minimum];//listb outer = list minimum
            List[minimum] = int.MaxValue;//set the list minimum to a dummy value 
        }
        Debug.log(ListB[0] + "," + ListB[1] + "," + ListB[2] + "," + ListB[3] + "," + ListB[4]);
        Debug.log(List[0] + "," + List[1] + "," + List[2] + "," + List[3] + "," + List[4] + ",");