归并排序
算法思想
分治思想
时间复杂度和空间复杂度
归并排序最好和最坏情况的时间复杂度都是O(n)log(n),空间复杂度度是O(n)
稳定性
稳定
python实现
def merge_sort(nums, left, right, result): if right != left: merge_sort(nums, left, (right+left)//2, result) merge_sort(nums, (right+left)//2+1, right, result) merge(nums, left, right, result) for i in range(left, right+1): nums[i] = result[i] def merge(nums, left, right, result): mid = (right+left)//2 k = left p = mid + 1 while left <= mid: if p <= right: if nums[left] < nums[p]: result[k] = nums[left] k += 1 left += 1 else: result[k] = nums[p] k += 1 p += 1 else: result[k] = nums[left] k += 1 left += 1 for i in range(p, right+1): result[k] = nums[p] k += 1 p += 1 if __name__ == '__main__': nums = list(map(int, input().strip().split(' '))) result = [0] * len(nums) merge_sort(nums, 0, len(nums)-1, result) print(result) print(nums)
C++实现
int merge(int nums[], int left, int right, int result[])
{
int mid = (left + right) / 2;
int i = left;
int j = mid + 1;
int k = left;
while(i <= mid)
{
if(j <= right)
{
if(nums[i] < nums[j])
{
result[k] = nums[i];
k++;
i++;
}
else
{
result[k] = nums[j];
k++;
j++;
}
}
else
{
result[k] = nums[i];
k++;
i++;
}
}
while(j <= right)
{
result[k] = nums[j];
k++;
j++;
}
}
void merge_sort(int nums[], int left, int right, int result[])
{
if(left < right)
{
merge_sort(nums, left, (left+right)/2, result);
merge_sort(nums, (left+right)/2+1, right, result);
merge(nums, left, right, result);
for(int i=left; i<=right; i++)
nums[i] = result[i];
}
}