如何在Java中选择排序打印第4次迭代以及以下测试用例的解决方案

问题描述 投票:1回答:2

使用选择排序对给定的一组数字进行排序。

输入的第一行包含元素的数量,输入的第二行包含要排序的数字。在输出中打印第4次迭代时数组的状态以及给定格式的最终​​排序数组

Logic Test Case 1

Input (stdin)
5

25 47 11 65 1

Expected Output

1 11 25 65 47 

Sorted Array:

1 11 25 47 65
Logic Test Case 2

Input (stdin)
7

14 83 25 47 9 77 1

Expected Output

1 9 14 47 83 77 25 

Sorted Array:

1 9 14 25 47 77 83

请尝试在Java中解决此问题。

java sorting selection-sort
2个回答
2
投票

我想问你为什么需要打印第4次迭代?但是另一方面,您可以实现选择排序算法并计算循环中的迭代次数,当计数为四时,您可以打印并继续整个循环,直到对完整的数字集进行排序。

public class SelectionSort {

  public SelectionSort() {

  }

  int [] a={1 ,11 ,25 ,65 ,47 };

  public void getSorted(){

  for(int i=0;i<a.length-1;i++){

    if(i==3) {

      for (int o = 0; o < a.length; o++)
        System.out.printf("%d ",a[o]);

      System.out.println();

    }

    int min=i;
    boolean depend=false;

    for(int j=i;j<a.length-1;j++){

      if(a[min] > a[j+1]) {

        min = j + 1;
        depend=true;

      }

    }

    if(depend==true)
      this.swap(i,min);

  }

    System.out.println("Sorted array :");

  for(int i=0;i<a.length;i++)
    System.out.printf("%d ",a[i]);

  }

  private void swap(int i, int min){

    int temp=a[i];
    a[i]=a[min];
    a[min]=temp;

  }

}

在此特定选择排序算法中,当您要打印第4次迭代时,它将在i==3返回true时打印数组。我们希望在第4次迭代中i3,因为我们从0索引了一个数组。


1
投票

下面的代码可以按您期望的方式工作。

PS-确保您自行尝试,而不要直接询问一个问题。

import java.util.Arrays;

public class SelectionSort {

private static void sort(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
        int minIdx = i;
        for (int j = i + 1; j < n; j++)
            if (arr[j] < arr[minIdx])
                minIdx = j;

        // Swap number to correct position
        int temp = arr[minIdx];
        arr[minIdx] = arr[i];
        arr[i] = temp;
        if (i == 2) { // 0 based index, 2 - is the fourth iteration [n-1]
            print(arr);
        }
    }
}

private static void print(int[] arr) {
    Arrays.stream(arr).forEach(value -> System.out.print(value + " "));
    System.out.println();
}

public static void main(String[] args) {
    // Test 1
    int[] arr1 = new int[]{25, 47, 11, 65, 1};
    sort(arr1);
    print(arr1);


    // Test 2
    int[] arr2 = new int[]{14, 83, 25, 47, 9, 77, 1};
    sort(arr2);
    print(arr2);
}
© www.soinside.com 2019 - 2024. All rights reserved.