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 1 year has passed since last update.

一番シンプルなソートをPythonで実装してみた

Posted at

目標は題目の通り。ソートには色々あるが一番シンプルと思われるソートをPythonで実装してみました。
ソースコードは以下の通り。やってる内容は、data内にランダムな数値データを格納する。ソート前のデータを表示する。その後data2にdataのデータをコピーする。data2のデータをソートする。data2の中身を表示してソートできているかを確認する。

sort.py
import random

data = {}
data2 = {}
NUM = 10
i = 0
while i < NUM:
    data[i] = random.random()
    i = i + 1

#show
def show_data():
    print("==>> show data")
    i = 0
    while i < NUM:
        print ( str(i) + ":" + str(data[i]) )
        i = i + 1

def show_data2():
    print("==>> show data2")
    i = 0
    while i < NUM:
        print ( str(i) + ":" + str(data2[i]) )
        i = i + 1
#copy
def copy_data_to_data2():
    print("==>> copy data to data2")
    i = 0
    while i < NUM:
        data2[i] = data[i]
        i = i + 1

#sort
def simple_sort():
    print("==>> simple sort")
    i = 0
    while i < NUM:
        j = 0
        while j < NUM:
            if data2[i] < data2[j]:
                tmp = data2[i]
                data2[i] = data2[j]
                data2[j] = tmp
            j = j + 1
        i = i + 1

show_data()
copy_data_to_data2()
simple_sort()
show_data2()

実行結果は以下の通り。

$ python3 sort.py 
==>> show data
0:0.2613891481899041
1:0.3412178877384152
2:0.49796534410121984
3:0.2780476378903276
4:0.42067892792019757
5:0.7197710392631774
6:0.4928607169460524
7:0.8219260610859638
8:0.3325716632887812
9:0.9467871389339843
==>> copy data to data2
==>> simple sort
==>> show data2
0:0.2613891481899041
1:0.2780476378903276
2:0.3325716632887812
3:0.3412178877384152
4:0.42067892792019757
5:0.4928607169460524
6:0.49796534410121984
7:0.7197710392631774
8:0.8219260610859638
9:0.9467871389339843

なにかの役に立てばと。

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?