快速排序之算法导论实现

算法导论 - 基于 C# 的快速排序算法实现 快速排序是一种高效的排序算法,通过递归调用和分治策略,可以有效地对大规模数据集进行排序。通过本文档,您应能够理解快速排序的基本原理及其实现,并能够在合适的场景中应用这一算法。 阅读详情

#include <iostream>
using namespace std;
int partition(int *a,int p,int r)
{
	int x=a[r];
	int i=p-1;//note i important which is used for 
				//storage the number smaller than flag x=a[r]
	for (int j=p;j<r;j++)
	{
		if (a[j]<x)// if a[j] smaller than x=a[r],
					//exchange a[i+1] and a[j]
		{
			i++;
			int t=a[j];
			a[j]=a[i];
			a[i]=t;
		}
	}
	int t=a[i+1];// i+1 is the a[r] final position
				//  exchange a[r] and a[i+1]
	a[i+1]=a[r];
	a[r]=t;
	return i+1; //return the a[r] final position i+1
}
void quicksort(int *a,int p,int r)
{
	if (p<r)//the position lower than the higher
	{
		int q=partition(a,p,r);//q is the a[r] final position
						// depart the arry[p...q-1] and arry[q+1...r]
		quicksort(a,p,q-1);
		quicksort(a,q+1,r);
	}
}
int main()
{
	int arry[]={3,2,1,4,5,6,9,8,7,0};
	quicksort(arry,0,9);
	for (int i=0;i<10;i++)
		cout<<arry[i]<<" ";
	cout<<endl;
}




import java.util.Scanner;

public class QuickSort {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner=new Scanner(System.in);
		int n=Integer.parseInt(scanner.next());
		int a[]=new int[n];
		for (int i = 0; i < a.length; i++) {
			a[i]=Integer.parseInt(scanner.next());
		}
		quickSort(a, 0, n-1);
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i]+" ");
		}
	}
	
	public static void  quickSort(int a[], int p, int e) {
		if (p<e) {
			int q=partion(a, p, e);
			quickSort(a, p, q-1);
			quickSort(a, q+1, e);
		}
	}
	public static int partion(int a[], int p, int e) {
		int x=a[e];
		int j=p-1;
		for (int i = p; i < e; i++) {
			if (a[i]<x) {
				j++;
				int t=a[i];
				a[i]=a[j];
				a[j]=t;
			}
		}
		int t=a[j+1];
		a[j+1]=a[e];
		a[e]=t;
		return j+1;
	}
}	
//	public static <T> void  swap (T  a, T b) {
//		T temp=b;
//		b=a;
//		a=temp;
//	}





加权余量法求解偏微分方程 加权余量法(Weighted Residual Method)是一种数值方法,用于求解偏微分方程(PDEs)。其基本思想是将偏微分方程的残差(或余量)通过加权函数加权,并使加权余量在定义域上为零,从而形成一组代数方程进行求解。 阅读详情

相关推荐

2.8 快速排序

快速排序是基于分治法的排序方法。可以分以下三个步骤: 1,分解:以a[p]为基准,将数组a[p,r]划分为3部分,分别是a[p,q-1],a[q],a[q+1,r]其中a[p,q-1]中的元素小于a[q],a[q+1,r]中的元素大于a[q],下标q在划分中确定。 2,递归求解:通过递归调用快速排序算法,对a[q]两边的数组快速排序。 3:合并:a[p,q-1]和a[q+1,r]已经排好序了,排序完成。 #include<iostream> using namespace std; i

qq_45887957的博客 207

RGMII时序约束

RGMII时序约束

wudpekerlily的博客 5075

快速排序法递归实现--C语言

以下是快速排序法的递归实现,使用C语言编写: #include <stdio.h> void Sort(int a[],int p,int r); int partition(int a[],int p,int r); void Swap(int a[],int i,int j); int main() { int n,a[100],p,r; //...

GG_freedom 1547

高德地图+Three.js实战:手把手教你打造数字农场3D可视化大屏(附完整源码)

本文详细介绍了如何利用高德地图JS API与Three.js技术栈,构建一个功能强大的数字农场3D可视化大屏。文章从技术选型、架构设计出发,深入讲解了坐标对齐、图层管理、性能优化等核心工程实践,并提供了完整的模块化代码示例,旨在为智慧农业及类似场景的3D地理可视化项目提供一套可复用的解决方案。

k8s6orchestrator的博客 895

GPD源码分析

gpd使用示例 先看下面一段代码,为标准gpd算法的使用方法,可以看到输入为点云,cloud_camera_; 输入:std::unique_ptr<gpd::util::Cloud> cloud_camera_ 输出: std::vector<std::unique_ptr<gpd::candidate::Hand>> grasps; // detect grasp poses gpd对象:std::unique_ptr<gpd::GraspDetect.

weixin_41003113的博客 2335

C++自定义数组长度的快速排序的代码

下面的内容是关于C++自定义数组长度的快速排序的内容,应该是对小伙伴有所用。 #include<stdio.h> #include<stdlib.h> void Swap(int &a,int &b) { int temp=a;a=b;b=temp; } int Partition(int a[],int p,int r) { int i=p,j=r+1; ...

weixin_34128534的博客 526

primetime如何做voltage scaling

存在这样的情况,标准单元库只有ssgnp0p72vm40c和ssgnp0p9vm40c的libs,但是我们希望它工作在ssgnp0p76vm40c,这样的话就需要用ssgnp0p72vm40c和ssgnp0p9vm40c的libs来scaling出ssgnp0p76vm40c的lib。

qq_34326957的博客 1691

int Partition(int a[],int p,int r)

int Partition(int a[],int p,int r)   {    int x = a[r];    int i = p - 1;    for(int j = p;j  {     if(a[j]   {      i = i + 1;      exchange(a+i,a+j);     }    }    exchange(a

菲尼克斯罗的学习笔记 1740

通过情感分类实例 详细介绍如果借助Huggingface平台 完成Transformers模型运行(包括配置环境-tokenizer-Model-输出头-预测)

attention_mask和padding是配套使用的,当人为去修改padding的时候,也要把attention_mask里面的参数进行修改。下载Huggingface包,Huggingface可以说是一个社区,集成了很多nlp的模型、数据集、预训练权重文件等等,并且免费,只需要pip install下载即可。那么用什么做分类就选择什么输出头,就import什么东西。代码中使用了自动分词器选择,它是由checkpoint指定的预训练模型关联的,不用我们自己选择tokenizer,它自动帮我们选择好了。

LZL2020LZL的博客 1140

深入理解 DDR5 Bank Group 与并行调度机制

Bank Group架构和并行调度机制,是DDR5性能跃升的核心秘密!理解它们才能写出高效调度程序,设计出性能强劲又稳定的DDR5系统。🎯记住:Bank Group不是简单的分组,而是高速并行的“魔法钥匙”,巧用它,你的DDR5设计将爆发惊人性能!

weixin_43199439的博客 322

算法导论-第7章-快速排序算法

#include int partition(int A[],int p,int r) { int x=0;int i=0; int temp=0; int temp1=0; int j=0; int k=0; x=A[r]; i=p-1; printf("before A[r] is %d\n",A[r]); for(j=p;j<=

wuxizhi777的专栏 469

银行业数据科学家的 6 条经验教训

原本希望在计算机科学、统计学和机器学习领域工作。运用新方法获得独特见解,实现一切自动化。简而言之,最终成了这个职业炒作的牺牲品。我想和你们分享一下。希望我们能够摆脱炒作,提高你对数据科学家工作的理解。

茶桁专栏 253

《算法导论》伪代码C++实现--快速排序

《算法导论》第7章快速排序 /** * 快速排序 */ #include <bits/stdc++.h> using namespace std; int partition(int A[], int p, int r){ int i = p-1; for (int j = p; j <= r-1; ++j) { if (A[j] <...

edestiny1的博客 782

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

算法导论——关于快速排序的实现(c语言实现)

在算法导论的第七章,介绍了有关快速排序的算法。该算法其实是分治算法的一种。 分:将数组中的元素分成两部分和一个pivot; 治:递归的对两个子数组进行排序; 合:此时将数组遍历输出即可; 书中介绍的算法的主要思想如下: 1、首先将数组的第一个元素作为pivot,然后顺序的遍历该数组,将小于pivot的元素同当前位置的下一个位置的元素交换; 2、该过程直到遍历到数组最后一个元素为止,最终

u011746585的专栏 471

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

算法导论第七章-快速排序-Cpp代码实现

实现了算法导论第七章中的快速排序

YY的博客 860

深度学习工具包 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")

[算法导论] 快速排序以及最大堆的C++实现

前言 重读了经典的>时,我把书上的部分代码用C++实现,然后与自己之前写的代码对比一下,不禁为>中算法实现的精简和优美所折服。今天把代码堆出来,以备不时之需。 快速排序 /* * 2013-02-02 22:20 mingspy 算法导论 */ #pragma once #include #include #include using std::cout; using

mingspy的专栏 919

【算法导论】用C++实现快速排序

本算法为【算法导论】7.1的C++实现,代码如下: #include void swap(int * a,int * b); int partition(int * array_list,int left,int right); void quick_sort(int * array_list,int left,int right); void Print(); const int size

Harry的专栏 1800

算法导论 - 快速排序的 C 语言实现

在实践中,需要对大量数据排序时,快速排序常常是最佳的选择。快速排序是基于分治思想的一种算法,和归并排序有相似之处。在最坏情况下,快速排序的时间复杂度是O( n^2 );平均情况下,快速排序的时间复杂度是 O( n * lg n)。我们知道归并排序的时间复杂度是O( n * lg n),那么为什么在实践中会发现快速排序常常要优于归并排序呢?通过分析快速算法,我们可以发现最坏情况出现的概率极为小;而在

Live and Learn 1154

《算法导论的Java实现》 8 快速排序

《算法导论的Java实现》 8 快速排序

chen09的专栏 3721

算法导论 - QuickSort 快速排序 C++实现

算法导论的快速排序还和一般书上的快速排序是有点不一样的。 当然书习题也给出了一般快速排序的方法,其分区函数学名叫Hoare partition。 书本介绍的排序可以用图看的很清晰: 然后配合C++程序,就不需要废话就能明白了: 他的quick sort程序也很明了,值得注意到的地方就是,mid是已经到了最终排序位置的了,所以,不需要递归考虑这个位置了。

靖空间 2万+

快速排序(基于算法导论思想)的C语言实现

快速排序(算法导论版) #include <bits/stdc++.h> using namespace std; void swap(int &a,int &b){ int temp = a; a = b; b = temp; } int parttion(int a[],int l,int r){ int x = a[r...

HJM916577的博客 568

算法导论---快速排序实现

package Search; //快速排序算法导论 public class QuickSort1 { public static void main(String[] args) { int arr[] = { 49, 38, 65, 97, 76, 13, 27 }; QuickSort1 q = new QuickSort1(); q.quicksort(arr, 0, arr.le...

shitiezhu的博客 303

算法导论的C++实现——5.快速排序

快速排序概述 对于包含n个数的输入数组来说,快速排序是一种最坏情况时间复杂度为O(n^2)的排序算法。虽然最坏情况时间复杂度很差,但是快速排序通常是实际排序应用中最好的选择,因为它的平均性能非常好:它的期望时间复杂度是O(nlgn),而且O(nlgn)中隐含的常数因子非常小。 快速排序的描述 与归并排序一样,快速排序也使用了分治思想。下面是对一个典型的子数组A[p…r]进行快速排序的三步分治过程: 分解:数组A[p…r]被划分为两个(可能为空)子数组A[p…q - 1]和A[q + 1…r],使得A[p…q

qq_42426141的博客 333

算法导论--快速排序JS实现

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-U...

qq_44363897的博客 163
上一篇: C# 窗体间传递数据
下一篇: 实习第四周
cypher_forward
博客等级 码龄17年 270粉丝 33原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值