병합정렬(Merge Sort)
방법
- 배열을 절반으로 계속 나눈다(원소가 1개가 될때까지 재귀적으로)
- 각 부분 리스트를 재귀적으로 합병 정렬을 이용해 정렬한다
구현
Python
def merge_split(data):
if len(data) <= 1:
return data
medium = int(len(data) / 2)
left = mergesplit(data[:medium])
right = mergesplit(data[medium:])
return merge(left, right)
def merge(left, right):
merged = list()
left_point, right_point = 0, 0
while len(left) > left_point and len(right) > right_point:
if left[left_point] > right[right_point]:
merged.append(right[right_point])
right_point += 1
else:
merged.append(left[left_point])
left_point += 1
while len(left) > left_point:
merged.append(left[left_point])
left_point += 1
while len(right) > right_point:
merged.append(right[right_point])
right_point += 1
return merged
Swift
func mergeSplit(_ data: [Int]) -> [Int] {
if data.count <= 1 {
return data
}
let medium = (data.count) / 2
let left = mergeSplit(Array(data[0..<medium]))
let right = mergeSplit(Array(data[medium..<data.count]))
return merge(left: left, right: right)
}
func merge(left: [Int], right: [Int]) -> [Int] {
var merged: [Int] = []
var leftPoint = 0
var rightPoint = 0
while left.count > leftPoint, right.count > rightPoint {
if left[leftPoint] > right[rightPoint] {
merged.append(right[rightPoint])
rightPoint += 1
} else {
merged.append(left[leftPoint])
leftPoint += 1
}
}
while left.count > leftPoint {
merged.append(left[leftPoint])
leftPoint += 1
}
while right.count > rightPoint {
merged.append(right[rightPoint])
rightPoint += 1
}
return merged
}
테스트
var data = [44, 55, 72, 83, 74, 57, 86, 71, 85, 75, 17, 67, 59, 82, 7, 88, 13, 68, 19]
print(mergeSplit(data))