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 BubbleSort {
  
  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 swap_count = bubbleSort(data_array);//バブルソート
      printResult(data_array, swap_count); //結果出力

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

    }
  }

  public static int bubbleSort(int[] data_array){
    int swap_count = 0;
    int tmp = 0;

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

        //入れ替え
        if(data_array[i] < data_array[j]){
          tmp = data_array[i];
          data_array[i] = data_array[j];
          data_array[j] = tmp;
          swap_count++;
        }
      }
    }

    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?