【问题标题】:How to loop through Selection Sort in Java?如何在Java中循环选择排序?
【发布时间】:2015-04-29 12:23:19
【问题描述】:

我想展示选择排序的每次迭代以打印出它是如何工作的,我将如何循环和打印它?我让它在它已经排序后打印输出。这是我的代码:

public class TestSelectionSort {

    public static void main(String[] args) {

        int list[] = { 2, 56, 34, 25, 73, 46, 89, 10, 5, 16 };

        selectionSort(list, list.length);

        System.out.println("After sorting, the list elements are:");

        for (int i = 0; i < list.length; i++) {
            System.out.print(list[i] + " ");
        }

    }

    public static void selectionSort(int[] list, int listLength) {
        int index;
        int smallestIndex;
        int minIndex;
        int temp;

        for (index = 0; index < listLength - 1; index++) {
            //Step a
            smallestIndex = index;

            for (minIndex = index + 1; minIndex < listLength; minIndex++)
                if (list[minIndex] < list[smallestIndex])
                    smallestIndex = minIndex;

            //Step b
            temp = list[smallestIndex];
            list[smallestIndex] = list[index];
            list[index] = temp;

        }

    }
}

【问题讨论】:

    标签: java selection-sort


    【解决方案1】:

    您可以通过在选择排序的外部循环末尾添加一个打印语句来做到这一点。例如。 :

    public static void selectionSort(int[] list, int listLength) {
            int index;
            int smallestIndex;
            int minIndex;
            int temp;
    
            for (index = 0; index < listLength - 1; index++) {
                //Step a
                smallestIndex = index;
    
                for (minIndex = index + 1; minIndex < listLength; minIndex++)
                    if (list[minIndex] < list[smallestIndex])
                        smallestIndex = minIndex;
    
                //Step b
                temp = list[smallestIndex];
                list[smallestIndex] = list[index];
                list[index] = temp;
    
                System.out.println("Printing data for iteration no " + index);
                printData(list);
    
            }
    
        }
    
        private static void printData(int[] list) {
            for (int i = 0; i < list.length; i++) {
                System.out.print(list[i] + " ");
            }
    
            System.out.println();
        }
    

    【讨论】:

      【解决方案2】:

      只需复制您用于打印最终结果的 sn-p:

      for(int i = 0; i < list.length; i++)
      {
          System.out.print(list[i] + " ");
      }
      

      selectionSort()中的循环结束之前。

      【讨论】:

      • 非常感谢...我想我试过了,不过我可能已经把它放在我的循环之外了。
      猜你喜欢
      • 2018-09-19
      • 1970-01-01
      • 2013-11-01
      • 2014-03-15
      • 1970-01-01
      • 2018-01-07
      • 1970-01-01
      • 2019-02-21
      • 2013-04-13
      相关资源
      最近更新 更多