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

double selection sort までpython で書いてみた

Posted at

wiki の選択ソートを見たところ
最小最大を同時の確定させるロジックのことを
double selection sort

と呼ぶらしいことを知った
初めて知った・・・お勉強タイムなのでこれを今日は書いてみることにしました
とらあえずは昇順ソートと降順ソートを書いてみまして
これらを同時に行う感じですが・・・
最小 と 最大 が入り組んだ場合の考慮が必要だったのですが
もっとスマートに書けるのではないかな。
残課題となりました。

selection_sort_asc
#昇順(最小値を先頭に移動)
def selection_sort_asc(A):
    for i in range(len(A)):
        min = i
        for j in range(i+1, len(A)):
            if A[j] < A[min]:
                min = j
        A[i], A[min] = A[min], A[i]
selection_sort_desc
#降順(最大値を先頭に移動)
def selection_sort_desc(A):
    for i in range(len(A)):
        max = i
        for j in range(i+1, len(A)):
            if A[j] > A[max]:
                max = j
        A[i], A[max] = A[max], A[i]
selection_sort_asc2
#昇順(最大値を最後尾に移動)
def selection_sort_asc2(A):
    for i in range(len(A)):
        max = len(A)-1-i
        for j in range(len(A)-1-i):
            if A[j] > A[max]:
                max = j
        A[len(A)-1-i], A[max] = A[max], A[len(A)-1-i]
double_selection_sort
#昇順(最小値を先頭に、最大値を最後尾移動、両方同時に移動)
def double_selection_sort(A):
    for i in range(len(A)//2):
        min = i
        max = len(A)-i-1
        for j in range(i,len(A)-i):
            if A[j] < A[min]:
                min = j
            if A[j] > A[max]:
                max = j
        A[len(A)-1-i], A[max] = A[max], A[len(A)-1-i]
        if min !=len(A)-1-i:
          A[i], A[min] = A[min], A[i]
        else:
          A[i], A[max] = A[max], A[i]
実行結果
LL = [7,4,3,17,14,13, 11, 12,15, 1, 2,5]
L=LL
print("src",L)
# src [7, 4, 3, 17, 14, 13, 11, 12, 15, 1, 2, 5]

double_selection_sort(L)
print("double_selection_sort",L)
# double_selection_sort [1, 2, 3, 4, 5, 7, 11, 12, 13, 14, 15, 17]

L=LL
selection_sort_asc(L)
print("selection_sort_asc",L)
# selection_sort_asc [1, 2, 3, 4, 5, 7, 11, 12, 13, 14, 15, 17]

L=LL
selection_sort_desc(L)
print("selection_sort_desc",L)
# selection_sort_desc [17, 15, 14, 13, 12, 11, 7, 5, 4, 3, 2, 1]

L=LL
selection_sort_asc2(L)
print("selection_sort_asc2",L)
# selection_sort_asc2 [1, 2, 3, 4, 5, 7, 11, 12, 13, 14, 15, 17]

L=LL
double_selection_sort(L)
print("double_selection_sort",L)
# double_selection_sort [1, 2, 3, 4, 5, 7, 11, 12, 13, 14, 15, 17]

exit()
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?