其他分享
首页 > 其他分享> > 分治法之二路归并排序

分治法之二路归并排序

作者:互联网

文章目录


二路归并排序


一、大概思路

在这里插入图片描述

二、代码实现

# -*- coding: utf-8 -*-
"""
Created on Tue Nov 16 09:34:33 2021

@author: lenovo
转载:https://blog.csdn.net/u010339879/article/details/78251211?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522163729649116780264024251%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=163729649116780264024251&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-2-78251211.pc_search_es_clickV2&utm_term=%E4%BA%8C%E8%B7%AF%E5%BD%92%E5%B9%B6%E6%8E%92%E5%BA%8Fpython&spm=1018.2226.3001.4187
"""

array = [32,15,11,26,53,87,3,61]
def  Merge(array,low,middle,high):
    n1 = middle -low +1;
    n2 = high-middle
    left_array=[]
    right_array=[]
 
    # 可以理解相当于申请一块空间
    for t in range(0, int(n1)):
        left_array = ['0'] + left_array
 
    for t in range(0, int(n1)):
        right_array = ['0'] + right_array
 
    # 把array 左边的值,放到left_arr  数组里面
    for i in range(0,n1):
        left_array[i]=array[i+low]
 
    # 把 array 右边的值,放到 right_arr  数组里面
    for j in range(0,n2):
        right_array[j]=array[j+middle+1]
 
    i,j =0,0
    k = low
    while  i!=n1 and j !=n2:
        if left_array[i]<= right_array[j]:
            array[k]=left_array[i]
            k += 1
            i += 1
        else:
            array[k]=right_array[j]
            k += 1
            j += 1
 
           
    while i < n1:
        array[k]=left_array[i]
        k += 1
        i += 1
 
    while j< n2:
        array[k]=right_array[j]
        k += 1
        j += 1
 
 
def  MergeSort(array,p,q):
    if p< q:
        # 转成int  类型
        mid =int((p+q)/2)
        MergeSort(array,p,mid)
        MergeSort(array,mid+1,q)
        Merge(array,p,mid,q)

MergeSort(array, 0, 7)
print(array)

2.读入数据

代码如下(示例):

data = pd.read_csv(
    'https://labfile.oss.aliyuncs.com/courses/1283/adult.data.csv')
print(data.head())

下一篇

分治法之二分查找
注:代码转载之 博客csdn

标签:归并,right,二路,分治,range,2522%,n1,array,left
来源: https://blog.csdn.net/qq_48959845/article/details/121419895