zoukankan      html  css  js  c++  java
  • 算法导论(2)快速排序

    一、一般的快速排序

    QuickSort.h文件

    #pragma once
    /*交换两个数*/
    template<class T>
    void Swamp(T &a, T &b)
    {
    	T temp;
    	temp = a;
    	a = b;
    	b = temp;
    }
    /*
    将数组分为小于等于x,和大于x的两个部分
    其中这里x选择为数组的最后一个元素
    如当输入{ 2,8,7,1,3,5,6,4 }时,输出为{2,1,3,4,7,5,6,8},函数返回值为3,即数组中x的索引
    */
    template<class T>
    int Partition(T *src,int startIndex,int endIndex)
    {
    	T x = src[endIndex];
    	int i = startIndex - 1;
    	for (int j = startIndex; j < endIndex; j++) {
    		if (src[j] <= x) {
    			i++;
    			Swamp(src[i], src[j]);
    		}
    	}
    	Swamp(src[i + 1], src[endIndex]);
    	return i + 1;
    }
    /*
    快速排序算法
    对数组从startIndex-endIndex的元素进行排序
    */
    template<class T>
    void QuickSort(T *src, int startIndex,int endIndex)
    {
    	if (startIndex < endIndex) {
    		int middleIndex = Partition(src, startIndex, endIndex); //以middleIndex为界排列成左右两部分
    		QuickSort(src, startIndex, middleIndex - 1);		    //递归调用排列左侧一部分
    		QuickSort(src, middleIndex + 1, endIndex);		        //递归调用排列右侧一部分
    	}
    }

    二、快速排序的随机化版本

    RandomQuickSort.h

    #pragma once
    #include<stdlib.h>
    #include<math.h>
    #include<time.h>
    #include"QuickSort.h"
    
    #define random(a,b) (((double)rand()/RAND_MAX)*(b-a)+a)
    /*
    产生一个[a,b]区间内的随机数*/
    int Random(int a, int b)
    {
    	double r = random(a, b);
    	return int(r > 0 ? floor(r + 0.5) : ceil(r - 0.5));     //四舍五入
     }
    
    /*
    将数组分为小于等于x,和大于x的两个部分
    其中这里x选择为数组的最后一个元素
    如当输入{ 2,8,7,1,3,5,6,4 }时,输出为{2,1,3,4,7,5,6,8},函数返回值为3,即数组中x的索引
    */
    template<class T>
    int RandomPartition(T *src, int startIndex, int endIndex)
    {	
    	int i = Random(startIndex, endIndex);
    	Swamp(src[i], src[endIndex]);
    	return Partition(src,startIndex,endIndex);
    }
    
    /*
    快速排序算法
    对数组从startIndex-endIndex的元素进行排序
    */
    template<class T>
    void RandomQuickSort(T *src, int startIndex, int endIndex)
    {
    	if (startIndex < endIndex) {
    		int middleIndex = RandomPartition(src, startIndex, endIndex); //以middleIndex为界排列成左右两部分
    		RandomQuickSort(src, startIndex, middleIndex - 1);		    //递归调用排列左侧一部分
    		RandomQuickSort(src, middleIndex + 1, endIndex);		        //递归调用排列右侧一部分
    	}
    }
    
     
  • 相关阅读:
    iot 表索引dump《2》
    heap表和iot表排序规则不同
    Cannot complete the install because one or more required items could not be found.
    iot表输出按主键列排序,heap表不是
    iot 表主键存放所有数据,且按数据插入顺序排序
    iot表和heap表排序规则不同
    org.eclipse.graphiti.ui.editor.DiagramEditorInput.
    Oracle 排序规则
    perl 异步超时 打印错误
    14.6.3 Grouping DML Operations with Transactions 组DML操作
  • 原文地址:https://www.cnblogs.com/ql698214/p/5424865.html
Copyright © 2011-2022 走看看