Skip to content
This repository was archived by the owner on May 22, 2026. It is now read-only.

Commit 87badf2

Browse files
feat: insert sort written by Haskell
1 parent 23b15a7 commit 87badf2

3 files changed

Lines changed: 19 additions & 1 deletion

File tree

sort/insert_sort/insert_sort.hs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
-- 要素を正しい位置に挿入する関数
2+
insert :: Ord a => a -> [a] -> [a]
3+
insert e [] = [e] -- 空リストへの挿入
4+
insert e (x:xs)
5+
| e <= x = e:x:xs -- eをxの左へ
6+
| otherwise = x:insert e xs -- eをxsの適切な位置へ挿入
7+
8+
-- 挿入ソート関数
9+
insertSort :: Ord a => [a] -> [a]
10+
insertSort [] = []
11+
insertSort (x:xs) = insert x (insertSort xs)
12+
13+
main :: IO ()
14+
main = do
15+
let randomList = [30, 75, 69, 16, 47, 77, 60, 80, 74, 8, 77, 1, 60, 33, 70, 29, 24, 91, 60, 69]
16+
print randomList
17+
print $ insertSort randomList

sort/insert_sort/insert_sort.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ def insert_sort(array: List[int]) -> List[int]:
1414
# ループが1から始まっているのに注意。
1515
for i in range(1, len(array)):
1616
tmp = array[i]
17-
j = i
17+
j = i # jはtmpを挿入する位置を示すindex
1818

1919
# 取り出したtmpと取り出した位置よりひとつ左隣のarray[j-1]の値を比較し,tmpが小さければ入れ替える操作を繰り返す。
2020
while (j > 0) and (array[j - 1] > tmp):
@@ -27,6 +27,7 @@ def insert_sort(array: List[int]) -> List[int]:
2727
def main():
2828
random.seed(3) # randomシードを指定
2929
random_array = [random.randint(0, 99) for _ in range(20)]
30+
print(random_array)
3031
print(insert_sort(random_array))
3132

3233

sort/insert_sort/insert_sort_foldr.hs

Whitespace-only changes.

0 commit comments

Comments
 (0)