2
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.

Pythonを使ってsortを用いずリスト内の数を並べ替える。

Last updated at Posted at 2019-04-09

リスト内の数を並べ替えたい。

Pythonを使ってリスト内の数を並べ替えるのは、sortを使えば簡単です。しかしここではsortを使わない方法も併せて紹介します。


まずは sortを使って並べ替えてみる。

sortを使えば、簡単にできます。

# 適当に数のリストを作る。
T = [3,8,6,1,2,5,5,10,9,7]
print(T)

# 昇べきの順に並べ替える。
T.sort()
print(T)

# 降べきの順に並べ替える。
T.sort(reverse=True)
print(T)

sort を使わないで並べ替える。

ではsortを使わないで並べ替えるコードを書いていきます。

昇べきの順

T = [3,8,6,1,2,5,5,10,9,7]

# 昇べきの順に並べ替えるときは、まずリスト内のどの数よりも大きい数を後ろに加える。
T.append(100)

i = 0
while i < 10:
    j = 1
    while j < 10-i:
        if T[i] > T[i+j]:
            T[10] = T[i]
            T[i]=T[i+j]
            T[i+j]=T[10]
            T[10]=100
            j = j+1
        else:
            j=j+1
    i = i+1

# 加えた数を最後に取り除く。
T.remove(100)
print(T)

降べきの順にするときも同じようなコードです。

降べきの順
# 降べきの順に並べ替えるときは、まずリスト内のどの数よりも小さい数を後ろに加える。
T.append(-1)

i = 0
while i < 10:
    j = 1
    while j < 10-i:
        if T[i] < T[i+j]:
            T[10] = T[i]
            T[i]=T[i+j]
            T[i+j]=T[10]
            T[10]=100
            j = j+1
        else:
            j=j+1
    i = i+1

# 加えた数を最後に取り除く。
T.remove(-1)
print(T)
2
0
4

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
2
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?