0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

新卒SE選択ソート書いてみた

Posted at

基本情報技術者の擬似言語の学習のため実際にプログラム化してみました。
基本情報の問題集をもとにフローチャートを作成し、コーディングをおこなっております。

Qiita.java
import java.util.*;

public class SelectionSort {

  public static void main(String[] args){

    try {
      Scanner sc = new Scanner(System.in);
      System.out.println("作りたい配列の要素数を入力してください。降順に並べます。");
      int size = Integer.parseInt(sc.next()); 
      int[] data_array = new int[size]; 


      /*
       * テストデータ
       * 要素数 8
       * 47,33,68,55,74,89,25,10
       * 3,5,8,4,0,6,9,1
       * 7,7,7,7,7,6,9,1
       * 0,0,0,0,0,0,0,0
       * 80,70,60,50,40,30,20,10
       * 70,60,40,70,30,70,50,70
       * 80,60,40,70,30,10,50,20
       * 80,60,40,70,30,10,50,20
       * 80,60,40,70,30,10,50,70
       * 
       *
       */


      System.out.println("配列要素数が" + size + "個になるよう各要素に格納する値を入力してください");
      for (int i = 0; i < size; i++) {
        data_array[i] = Integer.parseInt(sc.next());
      }

      System.out.println("配列入力結果→" + Arrays.toString(data_array));

      int return_swap_count = selectionSort(data_array); //選択ソート
      printResult(data_array, return_swap_count); //結果出力


    } catch (Exception e) {
      System.out.println("エラー;" + e.getMessage());// エラーメッセージ表示
      e.printStackTrace(); // スタックトレース

    }
  }

  public static int selectionSort(int[] data_array){
    int range_max = 0;
    int range_max_index = 0;
    boolean flag = false;
    int tmp = 0;
    int swap_count = 0;

    //選択ソート
    for(int i = 0; i < data_array.length - 1; i++){
      range_max = data_array[i];
      range_max_index = i;
      for(int j = i + 1; j < data_array.length; j++){
        if(range_max < data_array[j]){
          range_max = data_array[j];
          range_max_index = j;
          flag = true;
        }
        
      }

      if(flag){
        tmp = data_array[i];
        data_array[i] = data_array[range_max_index];
        data_array[range_max_index] = tmp;

        swap_count++;
        flag = false;
      }
    }
    
    return swap_count;
  }


  public static void printResult(int[] data_array, int swap_count){
    System.out.println("選択ソート結果");
    System.out.println(Arrays.toString(data_array));

    System.out.println("交換回数は"+ swap_count + "回です。");
  }
  
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?