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 5 years have passed since last update.

忘備録_Logic_BubbleSort_1

0
Last updated at Posted at 2021-03-27

理解度がかなり中途半端なので理解が進む毎に更新していく。
かなり分かりにくい説明ですが自分なりの理解は進みました。

少し長いですが、自分なりの復習して理解できた

BubbleSort4.java


public class BubbleSort_4 {
	public static void sort1(int[] a) {
		int buf;//i,jの並び替えの為bufを用意
		for (int i = 0; i < 10; i++) {//全体の要素数10(0~9)
			for (int j = 0; j < 9; j++) {//最後は比較しないので全体の要素数から-1した数(0~8)
				if (a[j] > a[j + 1]) {//1と1の場合は比較されないのでスルーflase/条件分岐a[j]の次の要素a[j+1]が大きかったらtrue
					// j ループの時のa[j]を一旦bufに格納
					buf = a[j];
					//格納して空になったa[j]に次の要素のa[j-1]を格納する
					a[j] = a[j + 1];
					//次の要素のa[j-1]に一旦格納したbufを再度格納
					a[j + 1] = buf;
				}
			}
		}
		for (int b : a) {
			System.out.println(b);
		}
	}

	public static void main(String[] args) {
		var r = new Random();
		//要素数の初期化d
		int[] a = new int[10];
		int i;
		for (i = 0; i < 10; i++) {
			//a[i]番目に要素を入れていくr.nextInt(30)の代入
			a[i] = r.nextInt(30);
			System.out.println(a[i]);
		}
		//		int[] a = {1,1,13,57,8,2,54,3,5,33,};
		System.out.println("-------");
		sort1(a);
		}
	}



例として

1回目のループ0~9 i → 0
2回目のループ0~8 j → 0
例 num a{⑤,①,⑨}

s.java
if(a[j]//index[0num⑤]番
>
a[j+1])//index[1num①]番を比較
//この時trueになり
int buf = a[j]//⑤を代入
a[j] = a[j +1]//①を代入
//次の要素に
a[j+1] = buf //⑤を再度代入
//次の i → 0 j → 1 ループ時に a[j + 1]⑤はa[j]となり
//a[j]⑤とa[j+1]を再度比較するその為
//例 num はa{①,⑤}と入れ替わっている

次に

例 num a{①,⑤,⑨}
1回目のループ0~9 i → 0
2回目のループ0~8 j → 1

s.java
if(a[j])//a[index番号1 j ]⑤
>(a[j+1])//次の要素 ⑨
//を比較し式が成立しないのでfalse
///a{①,⑤,⑨}

この繰り返し

比較の時

昇順(1,2,3)>
降順(100,99,98)<

s.java
(a[j] > a[j + 1])
(a[j] < a[j + 1])

分かりやすかったので参考にしました

BubbleSort3.java

public class BubbleSort_3 {

	public static void main(String[] args) {
		int[] a = {5,3,9,1,8};
		int i, j,buf;

		for( i = 0; i < 5; i++) {
			for(j = 0; j < 4; j++) {
				if(a[j] > a[j + 1]) {
					buf = a[j];
					a[j] = a[j + 1];
					a[j + 1] = buf;
				}
			}
		}
	}
}

BubbleSort.java
public static void sort1(int[] a) {
//外側のループは大きな数字を確定させていくループ
//ループ変数iは0,1,2,3 = 4回ループが実行される
		for (int i = 0; i < 4; i++) {
//要素数から1引いた数
			for (int j = 0; j < 4 - i; j++) {
				if (a[j] > a[j + 1]) {//隣り合う要素との大小判定を行う
//a[j]の方が大きいので交換を行う
					int tmp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = tmp;
				}
			}
		}
		for(int b : a) {
			System.out.println(b);
		}
	}
	public static void main(String[] args) {
		int[] a = {10,4,5,6,1};
		sort1(a);

	}
実行
1 4 5 6 10
				}
			}
		}
	}
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?