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で挿入ソートを実装してみました。以下のページを参考にしました。
http://www1.cts.ne.jp/~clab/hsample/Sort/Sort2.html

ソースコード

上記のC言語のfor文をwhile文に書き換えました。あとはいっしょです。

insertion_sort.py
import random

data = {}
data2 = {}
temp = {}
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

#insertion_sort
def insertion_sort(array, n):
    print("==>> insertion sort")
    i = 0
    j = 0
    temp = 0
    i = 1
    while i < n:
        temp = array[i]
        j = i
        while j > 0 and array[j-1] > temp:
            array[j] = array[j - 1]
            j = j - 1
        array[j] = temp
        i = i + 1

copy_data_to_data2()
show_data2()
insertion_sort(data2, NUM)
show_data2()

実行結果

実行できました。アルゴリズムは正常に動いています。

$ python insertion_sort.py 
==>> copy data to data2
==>> show data2
0:0.869473256419
1:0.257731491847
2:0.913115196463
3:0.201501660522
4:0.00858543758708
5:0.587123873954
6:0.23756328504
7:0.524541808381
8:0.776380856197
9:0.00613001602015
==>> insertion sort
==>> show data2
0:0.00613001602015
1:0.00858543758708
2:0.201501660522
3:0.23756328504
4:0.257731491847
5:0.524541808381
6:0.587123873954
7:0.776380856197
8:0.869473256419
9:0.913115196463

何かの役に立てばと。

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?