LoginSignup
0
0

Pythonで書く「アルゴリズムとデータ構造」 12_バブルソート

Last updated at Posted at 2023-07-01

コーディングテスト対策として、「アルゴリズムとデータ構造」という本を実践してます。
自分自身の備忘のために、pythonコードとメモを載せてます。

pythonコード

# バブルソート関数の定義
def bubbleSort(A, N):
    # 交換回数
    swich_counter = 0
    neighbor_exist = True
    while neighbor_exist:
        neighbor_exist = False
        for j in reversed( range( N ) ):
            if A[ j ] < A[ j-1 ] and j-1 >= 0:
                tmp = A[ j ]
                A[ j ] = A[ j-1 ]
                A[ j-1 ] = tmp
                swich_counter = swich_counter + 1
                neighbor_exist = True
    return A, swich_counter


# いつものやつ(入力)
N_input = int( input() )
A_input = list( map( int, input().split(' ') ) )

# バブルソート関数の実行
A_output, swich_counter = bubbleSort(A_input, N_input)

# いつものやつ(出力)
print(' '.join( map( str, A_output) ) )
print(swich_counter)

補足

if A[ j ] < A[ j-1 ] and j-1 >= 0:

上記コードは j-1 >= 0 がないとループします。
理由は、pythonではA[-2]とかが出力できてしまうからです。

for j in reversed( range( N ) ):

上記コードは 5, 4, 3, 2, 1, 0 となります。

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