归并排序的循环实现

内部排序(四)归并排序的递归与循环实现 上一篇日志讲到了自己对堆排序的学习,堆排序时间复杂度能达到O(NlogN),且不需要额外的空间来存储排序过程中的有序序列,优点明显,不过堆排序不是稳定的,也就是说排序后相等数据之间的相对位置可能会发生改变。上一周的学习学到了一个同样时间复杂度为O(NlogN)的且是稳定的排序方法!那就是归并排序。 归并操作其实更多用在外部排序中- -、,是外部存储器最常用的排序方法,用分而治之的思想,下面会说。... 阅读详情

归并排序的循环实现的原理和递归是一样的,只是把递归改成了循环。
详情可戳:递归排序的递归实现
代码如下:

#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 110;
int n,one,A[maxn];
void merges(int A[],int L1,int R1,int L2,int R2){
    int i = L1,j = L2,temp[maxn],index = 0;
    while(i <= R1 && j <= R2){
        if(A[i] < A[j]) temp[index ++] = A[i++];
        else temp[index ++] = A[j++];
    }
    while(i <= R1) temp[index ++] = A[i++];
    while(j <= R2) temp[index ++] = A[j++];
    for(i = 0;i < index;i ++) A[L1 + i] = temp[i];
}
void mergesort(){
    for(int step = 2;step / 2 <= n; step *= 2){
        for(int i = 1;i <= n;i += step){
            int mid = i + step / 2 - 1;
            if(mid + 1 <= n){
                merges(A,i,mid,mid+1,min(i+step-1,n));
            }
        }
    }
}
int main(){
    cin >> n;
    for(int i = 1;i <= n;i ++){cin >> A[i];}
    mergesort();
    for(int i = 1;i <= n;i ++)   cout << A[i] << " ";
    return 0;
}
/*
sample input:
5
2 3 5 1 4
sample output:
1 2 3 4 5
*/

C++实现归并排序(使用循环实现) 在上一篇文章中实现了递归方法的归并排序。归并排序时间效率很好,虽然使用递归的方法实现很简单易读,但是容易造成空间性能上的损耗(反复的函数调用引起)。因此,有采用循环的方式实现归排序。给出了两种写法,一种是我自己写的(第一种),一种是weiss书上的课后习题的参考答案(第二种),思想是一样的,第二种明显比第一种写法简单很多。 阅读详情

相关推荐

python 归并排序的递归法与循环法(利用队列)实现,以及性能测试

python 归并排序的递归法与循环法(利用队列)实现,以及性能测试 递归排序核心 递归排序的核心是 分与合 分的最终结果 就是将原数组中每一个数字分作一个数组, 合就是 所有小数组不断排序,合并的过程。 合并的过程是先将两个含有一个数字的数组排序,合并(每次比较两个数组的最小值,将更小值加入新数组中,当有一个数组无元素,则将还有元素的数组追加到新数组中即完成排序,合并。新数组已是有序)为一个含有两个元素的有序数组。然后是两个含两个元素的有序数组排序合并为含四个元素的有序数组,两个含四个元素的有序数组合并为

lymmurrain的博客 774

归并排序-循环实现

归并排序是建立在归并操作基础上的一种排序方法。归并操作,是指将两个已排序的子序列合并成一个有序序列的过程归并操作的过程如下:申请额外空间用于放置两个子序列归并后的结果设置两个指针分别指向两个已排子序列的第一个位置比较两个指针指向的元素,并将较小的那个放到1中申请的空间内,当前指针向后移动一格重复3,直到某个子序列的指针指向该序列的结尾将另一序列剩余元素全部放入到1中空间内,归并操作结束/* 归并排...

热心市民小黎的博客 1026

归并排序的实现代码与思路

归并排序是建立在归并操作上的一种有效的排序算法。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。

排序篇:归并排序的递归,非递归以及计数排序的实现(C语言)

排序篇:归并排序的递归,非递归以及计数排序的实现(C语言)

2301_76269963的博客 1843

深入解析FDTD Script中的farfieldpolar3d命令:复电场计算与应用

本文深入解析了FDTD仿真中`farfieldpolar3d`命令的核心功能与应用。作为`farfield3d`的复数版本,该命令能计算并返回球坐标系下的复电场矢量,完整保留振幅与相位信息,为光学天线设计、近远场变换及偏振态分析等高级应用提供了关键数据基础。

grafana6viz的博客 287

基于OpenCV的驾驶疲劳检测与预警系统设计

PERCLOS(Percentage of Eye Closure)是一种基于眼睑闭合程度的疲劳度量指标。在基于OpenCV的驾驶疲劳检测与预警系统设计中,PERCLOS可以用于检测驾驶员的眼睑闭合程度,以判断其是否疲劳。该函数用于检测视频流中人脸的疲劳程度。具体地,该函数通过检测人脸的眼睛和嘴巴的状态来评估人脸的疲劳程度。眼睛状态是通过计算眼睛的长宽比(eyear)来判断,如果长宽比小于某个阈值,则认为眼睛闭合,表示人处于疲劳状态。

2301_79810943的博客 2327

2021年12月16日 归并排序(循环实现)&&快速排序

归并排序(循环) 模块一Merge_pass: "length = 当前有序子列的长度" void Merge_pass( ElementType A[], ElementType TmpA[], int N, int length ) { "两两归并相邻有序子列" int i, j; "首先并不全部归并,留下一个或者两个序列" for ( i=0; i <= N-2*length; i += 2*length ) Merge( A..

LEewhITe2003的博客 341

详解在linux上安装vpn客户端

详解在linux上安装vpn客户端

FuncPlotCalc 8432

归并排序

归并排序,是稳定的,不适合内排序,适合外排序,算法复杂度是O(Nlog(N)) 1、递归实现 /* 归并排序 - 递归实现 */ /* L = 左边起始位置, R = 右边起始位置, RightEnd = 右边终点位置*/ void Merge( ElementType A[], ElementType TmpA[], int L, int R, int RightEnd ) { /* 将...

金色的省略号 85

【深度学习基础】Temporal Fusion Transformer

从下向上看:全连接(Dense) → ELU(指数线性激活函数(比relu好点,有利于模型收敛)) → 全连接(Dense) → 门控线性单元(Gate)(Gated Linear Units (GLUs)) → Layernorm。:一方面,它可以进行静态上下文变量和动态变量的融合,另一方面,通过门控进行了特征选择操作,门控体现在GLU(门控线性单元)中,用了sigmoid控制信息的通过程度,具有良好的适应性,能够自动选择有效信息,自适应地调整网络复杂性。输入:主输入,可选的上下文向量c。

weixin_41838721的博客 1227

准确率、召回率、f1指标计算的区别

准确率是模型正确预测的样本占总样本的比例。

stephen147的博客 1415

归并排序的递归实现与循环实现

归并排序的递归实现与循环实现 思路 假设数组逻辑上被分为两个数组,这两个数组有序,想办法把这两个数组有序的添加到另一个等长的备用数组中。 具体做法: 设置两个指针分别指向两个数组的第一个元素 比较两个指针所在元素的大小,小的放到备用数组中,并且小的元素的指针后移,直到有一个指针到头越界 另一个没越界的数组元素依次放到备用数组中 将备用数组中的元素copy到原数组中 递归代码实现 /** * 归并排序 递归实现 */ public static void mergeSortD

weixin_44713050的博客 272

Sigmastar平台WDR调试实战:从参数解析到鬼影消除的完整指南

本文提供了Sigmastar平台宽动态(WDR)技术的实战调试指南。针对逆光、运动场景下的核心痛点,系统性地解析了从多曝光采集、HDR融合到色调映射的完整管线,并重点阐述了如何通过调整曝光比、运动阈值与调整曲线等关键参数,有效消除运动鬼影、平衡暗部噪声与细节,最终实现清晰稳定的图像效果。

Jerry的专栏 927

java归并排序(递归实现 & 循环实现)及其优化

1.递归实现的算法思路 ① 首先将区间左右均分成两部分,按照此方法不断向下划分,直至区间内只剩一个数据(递归) ② 然后相邻两两区间进行排序归并(递归) ③ 将临时空间temp中的数据拷贝到array中去 代码实现如下: 首先写出一个合并数据的方法: // 合并数据 [left,mid) [mid,right) private static void mergeData(int[] a...

HJY615main的博客 486

实战指南(一)SCAPS-1D太阳能电池模拟软件从零到一:模型构建与参数解析

本文详细介绍了SCAPS-1D太阳能电池模拟软件的使用方法,从模型构建到参数解析,帮助用户快速掌握这一免费且功能强大的工具。特别适合用于单结/多结电池的电学性能分析,涵盖钙钛矿电池等常见结构的模拟实践,并提供参数调试和收敛性问题处理的实用技巧。

weixin_30588675的博客 445

使用 MATLAB/Simulink 构建一个 核电站汽轮机与发电机协调控制系统 的仿真模型

在核电机组中,汽轮机-发电机系统是将核能最终转化为电能的关键环节。与火电机组不同,核反应堆的热惯性大、功率调节慢,因此汽轮机的控制策略需与反应堆特性相匹配,实现安全、稳定、高效的能量转换。维持发电机输出功率/频率稳定(响应电网调度)调节汽轮机进汽压力(匹配一回路蒸汽供应)实现“堆-机协调控制”保障机组在启停、变负荷、甩负荷等工况下的安全性本教程将带你使用构建一个核电站汽轮机与发电机协调控制系统汽轮机调速系统(调门控制)建模发电机与电网接口建模(同步机)

xiaoheshang_123的博客 189

归并排序递归和循环实现——学习笔记

归并排序是效率非常高的一种排序方式,和快速排序一样用了分治的思想。分治法的精髓在于将一个复杂问题分割成为多个简单的子问题,然后将子问题逐个解决,最终合并在一起以后就是复杂问题的解了。 归并排序对数组排序时有两种实现方式,一种是利用递归来实现,另一种利用循环来实现,也可以叫自顶向下的归并排序和自底向上的归并排序。两种实现方式略有不同,但是基本思想是一样的,那听我慢慢道来。   递归版 递归版...

jjwwwww的博客 2567

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

归并排序算法 递归及循环实现

第一步合并相邻长度为1的子数组段,这是因为长度为1的子数组段是已经排好序的。 用一次对数组arr的线性扫描就足以找出所有这些排好序的子数组段。然后将相邻的排好序的子数组段两两合并,构成更大的排好序的子数组段。 #include #include using namespace std; //递归思想归并排序 //void MergeSort(int a[],int left,int righ

catkint的博客 2211

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

【玩转八大排序②】归并排序(递归实现与循环实现)

归并排序的递归和循环两种实现方式,以及代码书写过程中的易错点剖析

罅隙的博客 1019

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

循环实现归并排序简单

归并排序 * 思想:把两个有序的序列归并为一个有序的序列 * 如何保证两个序列是有序的?两个序列中元素个数为1 public class MergetTest { public static void merge(int []array,int gap){ int left1=0; int left2=left1+gap-1; int right1=left2+1; int right2=right1+gap-1>array.

weixin_49263647的博客 385

归并排序循环实现(存用)

参考MOOC浙大数据结构,归并排序的非递归算法

cos的博客 502

数据结构学习/复习14--归并排序的递归与循环实现/计数排序

一、归并排序 1.递归实现 注意事项:即使排序的数字个数不为2的倍数也可正常分解,其思想没有规定一定要左右数目对称才可合并 注意事项:归并的思想还适用于外排序 2.递归改循环 注意事项:边界处理与非2的n次方倍的处理 版本1:全部归并完后一起用memcpy()函数复制回原处 版本2:归并一部分,memcpy()拷贝一部分 二、其他排序 1.计数排序 三、排序性能总结

Hncj2022的博客 353

python实现归并排序及其优化(相对有序待排数,自顶向下递归实现以及自下向上循环实现)

python实现归并排序及其优化 1、归并排序思想: mergeSort: 分完再排,自上向底。先把待排数分为两个小部分直至不能再分,再归并(排序)。 mergeSortBU:边分边排,自底向上,设置size merge: 将传入的left_arr,right_arr按从小到大的顺序,合并为一个列表result, 并返回result 2、可以通...

qq_27087743的博客 649

归并排序(非递归实现)

我们知道,递归实现的缺点就是会一直调用栈,而栈内存往往是很小的。所以,我们尝试着用循环的办法去实现归并排序。之气提到过,归并排序的基本思路是将待排序序列R[0…n-1]看成是n个长度为1的有序序列,将相邻的有序表成对归并,得到n/2个长度为2的有序表;将这些有序序列再次归并,得到n/4个长度为4的有序序列;如此反复进行下去,最后得到一个长度为n的有序序列。综上可知:归并排序其实要做两件事:(1)“分

一首小夜曲 1万+

递归,迭代循环两版归并排序c++实现

只有代码 递归版: #include<iostream> using namespace std; void merging(int*a,int head,int mid,int tail) { int len=tail-head+1,i=head,j=mid+1,index=0; int temp[len]={};//临时数组 while(i&lt...

世界第一帅的博客 582

归并排序Java实现

递归实现 public class MergeSort { private static void merge(Integer[] a, Integer[] aux, int lo, int hi, int mid) { for (int k = lo; k <= hi; k++) aux[k] = a[k]; int i = lo; int j = mid + 1; for (int k = lo;

FengLing的博客 108
上一篇: 归并排序的递归实现
下一篇: 快速排序
lvonge
博客等级 码龄7年 4粉丝 18原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值