MATLABの例:バブルソートアルゴリズム



Matlab Example Bubble Sorting Algorithm



バブルソートアルゴリズムの問​​題:

  • アルゴリズムの紹介:バブルソート法は、特定のシーケンスを想定した単純なソートアルゴリズムです。a 1、a 2、…a n a_1、a_2、…a_nアルゴリズムのプロセスは次のとおりです。

  • ステップ1:最初に比較するa 1 a_1a 2 a_2サイズの場合a 1> a 2 a_1> a_2、しましょうa 1 a_1a 2 a_2お互いに交換し、比較するa 2 a_2a 3 a_3同じサイズの場合a 2> a 3 a_2> a_3、しましょうa 2 a_2a 3 a_3比較するまで、お互いに交換するなど。a n − 1 a_ {n-1}a n a_nサイズの場合a n − 1> a n a_ {n-1}> a_n、しましょうa n − 1 a_ {n-1}a n a_n上記の操作を行った後、相互に交換します。a n a_nシーケンスの最大の要素になります。



  • ステップ2:まだからa 1 a_1a 2 a_2比較を開始し、最初のステップの方法に従います。違いは、比較するだけでよいということです。a n − 2 a_ {n-2}a n − 1 a_ {n-1}、約束a n − 1 a_ {n-1}はい前にn − 1 n-1要素の最大数。

  • ステップ3:上記のステップ2に従って、保証しますa i a_iはい前に私は私要素の最大数。ここでi = n − 2、n − 1、…1 i = n-2、n-1、…1、このように、最後の新しいシーケンスa 1、a 2、…a n a_1、a_2、…a_nこれは、小さいものから大きいものへの元のシーケンスの結果です。



  • MATLABプログラムの実装

%Date:2019-11-11 % Writer: Unknown Thirteen %% The purpose of this program is to use the bubble sorting algorithm to sort a known set of data function y = bubble_sort (A)% parameter A is vector or matrix if nargin==0 errordlg ('No parameters entered!', 'Error!') end if ischar(A) == 1 errordlg ('The input data contains characters or strings, can not be sorted!', 'Error!') error% error report terminates the program end m = size (A)% find the dimension of parameter A if m (1) == 1 | m (2) == 1% when parameter A is a vector and not a matrix n = length (A)% get the number of elements contained in vector A cloth else% when parameter A is a matrix instead of a vector n = m (1) * m (2)% gets the number of elements contained in matrix A A = reshape (A, 1, n)% matrix A is a vector end for i = 1:n-1 for j = 1:n-i if A(j) > A(j+1) temp = A (j)% core code A(j) = A(j+1) A(j+1) = temp end end end fprintf ('The result after sorting by bubble sorting algorithm is as follows: n n')% output sorting result for i = 1:n fprintf('%f ', A(i)) if mod(i,8) == 0 fprintf(' ') end end fprintf(' ') end %%
  • 例1:次のベクトルAを並べ替える
>> A = [1 6 9 8 13 6 9 5 20 15 36 27] >> bubble_sort(A) The result after sorting by the bubble sorting algorithm is as follows: 1.000000 5.000000 6.000000 6.000000 8.000000 9.000000 9.000000 13.000000 15.000000 20.000000 27.000000 36.000000
  • 例2:次の3次正方行列Bを並べ替えます
>> B = [2 3 8 9 6 7 15 32 17] >> bubble_sort(B) The result after sorting by the bubble sorting algorithm is as follows: 2.000000 3.000000 6.000000 7.000000 8.000000 9.000000 15.000000 17.000000 32.000000
  • 結論:上記のコードは、私の理解に従って編成および記述されています。エラーや不備がある場合は、私を訂正してください!