zoukankan      html  css  js  c++  java
  • 数据结构

    归并排序(merging sort) 具体解释 及 代码


    本文地址: http://blog.csdn.net/caroline_wendy


    归并排序(merging sort): 包括2-路归并排序, 把数组拆分成两段, 使用递归, 将两个有序表合成一个新的有序表.

    归并排序(merge sort)的时间复杂度是O(nlogn), 实际效果不如高速排序(quick sort)和堆排序(heap sort), 

    可是归并排序是稳定排序, 而高速排序和堆排序则不是.


    代码:

    /*
     * main.cpp
     *
     *  Created on: 2014.6.12
     *      Author: Spike
     */
    
    /*eclipse cdt, gcc 4.8.1*/
    
    #include <iostream>
    #include <algorithm>
    #include <iterator>
    
    using namespace std;
    
    /*參数: SR-输入数组, TR-输出数组, i至m:第一段有序, m+1至n:第二段有序*/
    void Merge (const std::vector<int> SR, std::vector<int>& TR, int i, int m, int n)
    {
    	int j , k;
    	for (j=m+1, k=i; i<=m && j<=n; ++k) {
    		if (SR[i] < SR[j])
    			TR[k] = SR[i++];
    		else
    			TR[k] = SR[j++];
    	}
    	if (i<=m)
    		std::copy((SR.begin()+i), (SR.begin()+m+1), TR.begin()+k);
    	if (j<=n)
    		std::copy((SR.begin()+j), (SR.begin()+n+1), TR.begin()+k);
    }
    
    /*參数: SR-输入数组, TR-输出数组, s:起始, t:末尾*/
    void MSort (const std::vector<int> SR, std::vector<int>& TR, int s, int t)
    {
    	std::vector<int> tempTR(SR.size());
    	if (s == t)
    		TR[s] = SR[s];
    	else {
    		int m = (s+t)/2; //平分SR, SR[s..m]和SR[m+1..t]
    		MSort(SR, tempTR, s, m); //前半段
    		MSort(SR, tempTR, m+1, t); //后半段
    		Merge(tempTR, TR, s, m, t); //排序
    		//copy(TR.begin(), TR.end(), ostream_iterator<int>(cout, " "));
    		//std::cout << std::endl;
    	}
    }
    
    void MergeSort (std::vector<int>& L) {
    	MSort(L, L, 0, L.size()-1);
    }
    
    int main (void)
    {
    	std::vector<int> L = {49, 38, 65, 97, 76, 13, 27, 49};
    	MergeSort(L);
    	copy(L.begin(), L.end(), ostream_iterator<int>(cout, " "));
    	std::cout << std::endl;
    	return 0;
    }
    

    输出:

    13 27 38 49 49 65 76 97 
    







  • 相关阅读:
    PHP之get请求用php脚本实现
    PHP之download
    PHP之缩略图
    PHP之upload
    文本域<textarea>将 替换成换行
    JSON中获取变量key的值
    emap表格checkbox属性默认勾选
    读取ORACLE数据库中BOLB形式数据在前端预览
    oracle常用语法
    批量删除本地仓库未下载完成的jar文件
  • 原文地址:https://www.cnblogs.com/llguanli/p/6972415.html
Copyright © 2011-2022 走看看