0
1

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.

【Python】安定したソートを実装してみたのでメモ

Last updated at Posted at 2020-10-30

問題

下記サイト参照

私の回答

import collections

def chk_before_tranp_bigger(now, before):
    return int(before[1]) > int(now[1])


def is_stable(inputs: list, sort_: list) -> str:
    """
    条件
    ・同じ数字のカード
    ・入力に出現する順序と同じ

    いったん、入力データのリストを数字をキーにグループ分けをする
    例)
        {
            '4': ['H4', 'S4'],
            '9': ['C9'],
            '3': ['C3']
        }
    """
    judge = 'Not stable'
    loop = True
    set_num = collections.defaultdict(list)
    for input_ in inputs:
        set_num[input_[1]].append(input_)

    for g, dl in set_num.items():
        if len(dl) <= 1:
            continue
        min_index = -1
        for d in dl:
            if min_index > sort_.index(d):
                loop = False
                break
            min_index = sort_.index(d)
        if not loop:
            break
    else:
        judge = 'Stable'

    return judge


def bubble_sort(n: int, a: list) -> (list, str):
    dl = a.copy()
    for i in range(n):
        for j in range(n-1, i, -1):
            if chk_before_tranp_bigger(dl[j], dl[j-1]):
                dl[j], dl[j-1] = dl[j-1], dl[j]
    return dl, is_stable(a,  dl)


def selected_sort(n: int, a: list) -> (list, str):
    dl = a.copy()
    for i in range(n):
        mini = i
        for j in range(i, n):
            if chk_before_tranp_bigger(dl[j], dl[mini]):
                mini = j
        if mini != i:
            dl[i], dl[mini] = dl[mini], dl[i]

    return dl, is_stable(a, dl)


n = int(input())
a = input().split()

sort_, judge = bubble_sort(n, a)
print(*sort_)
print(judge)

sort_, judge = selected_sort(n, a)
print(*sort_)
print(judge)
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?