Skip to content

Commit

Permalink
study: sorting algorithm
Browse files Browse the repository at this point in the history
# id: 문제 id를 숫자로 작성
# categories : 해당 문제의 유형을 ,로 구분하여 작성
# tags : 해당 문제의 태그를 ,로 구분하여 작성
# time : 해당 문제 풀이에 걸린 시간을 분단위 숫자로 작성
# try : 해당 문제에 몇번의 시도를 했는지 숫자로 작성
# help: 해당 문제에 외부의 도움을 받았는지 true/false로 작성
# url : 해당 문제의 url을 작성
id:
categories: []
tags: []
time:
try:
help: false
url:
  • Loading branch information
gogumaC committed Jun 25, 2024
1 parent 4ecb475 commit bcf8805
Show file tree
Hide file tree
Showing 5 changed files with 97 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/sortingAlgorithms/1_bubble_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
def bubble_sort(arr):
for i in range(len(arr)):
for j in range(len(arr)-i-1):
if arr[j]>arr[j+1]:
arr[j],arr[j+1]=arr[j+1],arr[j]
print(arr)

arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
12 changes: 12 additions & 0 deletions src/sortingAlgorithms/2_selection_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
def selection_sort(arr):
n=len(arr)
for i in range(n):
min_idx=i
for j in range(i,n):
if arr[j]<arr[min_idx]:
min_idx=j
arr[i],arr[min_idx]=arr[min_idx],arr[i]
print(arr)

arr = [29, 10, 14, 37, 13]
selection_sort(arr)
14 changes: 14 additions & 0 deletions src/sortingAlgorithms/3_insertion_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
def insertion_sort(arr):
n=len(arr)
for i in range(n):
current=arr[i]
j=i-1
while j>=0 and arr[j]>current:
arr[j+1]=arr[j]
j-=1
arr[j+1]=current

print(arr)

arr = [12, 11, 13, 5, 6]
insertion_sort(arr)
36 changes: 36 additions & 0 deletions src/sortingAlgorithms/4_merge_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
def merge_sort(arr):
if len(arr)<=1:
return arr
mid=len(arr)//2

left=merge_sort(arr[:mid])
right=merge_sort(arr[mid:])

return merge(left,right)

def merge(left,right):

i=j=0
merged=[]
while i<len(left) and j<len(right):
if left[i]<right[j]:
merged.append(left[i])
i+=1
else:
merged.append(right[j])
j+=1

merged.extend(left[i:])
merged.extend(right[j:])

return merged


arr = [38, 27, 43, 3, 9, 82, 10]
sorted_arr=merge_sort(arr)
print(sorted_arr)





26 changes: 26 additions & 0 deletions src/sortingAlgorithms/5_quick_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
def quick_sort(low,high,arr):
if high-low+1==1:
return
mid=low+(high-low)//2
pivot=arr[mid]
left=low
right=high

while left!=right:
while arr[right]>pivot:
right-=1

while arr[left]<pivot:
left+=1
if arr[left]>arr[right]:
arr[right],arr[left]=arr[left],arr[right]

if right-1>low: quick_sort(low,right-1,arr)
if right+1<high: quick_sort(right+1,high,arr)


arr = [10, 7, 8, 9, 1, 5]
quick_sort(0,len(arr)-1,arr)
print(arr)


0 comments on commit bcf8805

Please sign in to comment.