zoukankan      html  css  js  c++  java
  • 数据结构--数组 的一个经典算法

      
    /*******************************************************************
    Copyright(c) 2016, Harry He
    All rights reserved.
    Distributed under the BSD license.
    (See accompanying file LICENSE.txt at
    https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
    *******************************************************************/
    
    //==================================================================
    // 《剑指Offer——名企面试官精讲典型编程题》代码
    // 作者:何海涛
    //==================================================================
    
    #pragma once
    
    __declspec( dllexport ) int Partition(int data[], int length, int start, int end);
    /*******************************************************************
    Copyright(c) 2016, Harry He
    All rights reserved.
    Distributed under the BSD license.
    (See accompanying file LICENSE.txt at
    https://github.com/zhedahht/CodingInterviewChinese2/blob/master/LICENSE.txt)
    *******************************************************************/
    
    //==================================================================
    // ¡¶½£Ö¸Offer¡ª¡ªÃûÆóÃæÊÔ¹Ù¾«½²µäÐͱà³ÌÌâ¡·´úÂë
    // ×÷ÕߣººÎº£ÌÎ
    //==================================================================
    
    #include <stdlib.h>
    #include "Array.h"
    #include <exception>
    
    // Random Partition
    int RandomInRange(int min, int max)
    {
        int random = rand() % (max - min + 1) + min;
        return random;
    }
    
    void Swap(int* num1, int* num2)
    {
        int temp = *num1;
        *num1 = *num2;
        *num2 = temp;
    }
    
    int Partition(int data[], int length, int start, int end)
    {
        if(data == nullptr || length <= 0 || start < 0 || end >= length)
            throw new std::exception("Invalid Parameters");
    
        int index = RandomInRange(start, end);
        Swap(&data[index], &data[end]);
    
        int small = start - 1;
        for(index = start; index < end; ++ index)
        {
            if(data[index] < data[end])
            {
                ++ small;
                if(small != index)
                    Swap(&data[index], &data[small]);
            }
        }
    
        ++ small;
        Swap(&data[small], &data[end]);
    
        return small;
    }
  • 相关阅读:
    算法沉思录之算法的结构
    OSSpinLockLock加锁机制,保证线程安全并且性能高
    iOS 开源库系列 Aspects核心源码分析---面向切面编程之疯狂的 Aspects
    代码阅读沉思录:代码的灵、肉与骨
    iOS AOP框架Aspects实现原理
    最近还是太浮躁了,一周阅读一个开源库是值得的
    performSelector 多参调用的实现方案
    oc消息转发:forwardInvocation、签名、参量个数、SEL 相关测试
    isa class superclass metaclass
    ARC与Toll-Free Bridging
  • 原文地址:https://www.cnblogs.com/music-liang/p/12610799.html
Copyright © 2011-2022 走看看