其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
2.3-6 Insertion Sort with Binary Search

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

<< Introduction to algorithms >> ( Second Edition )


2.3-6 Insertion Sort with Binary Search

Observe that the while loop of line 5-7 of the Insertion Sort precedure in
Section 2.1 uses a linear search to scan ( backward ) through the sorted subarray
A[ 1 .. j - 1 ]. Can we use a binary search ( see Exercise 2.3-5 ) instead to improve
the overall worst-case running time of insertion sort to O( nlgn ) ?


Solution:

// 声明:本代码旨在实现原文的思想
// copyleft 2004    http://blog.csdn.net/mskia
// email:    [email protected]

#ifndef Insertion_Sort_with_Binary_Search_by_mskia
#define Insertion_Sort_with_Binary_Search_by_mskia

namespace cc {
    template< class T >
    void insertion_sort_with_binary_search( T *first , T *last ) {
        for ( T *i = first + 1; i <= last; ++i ) {
            T *left = first , *right = i - 1;
            while ( left <= right ) {
                T *mid = left + ( ( right - left ) >> 1 );
                if ( *i < *mid ) {
                    if ( *( mid - 1 ) < *i ) {
                        T bac = *i;
                        for ( T *p = i; p > mid; --p ) {
                            *p = *( p - 1 );
                        }
                        *mid = bac;
                        break;
                    } else {
                        right = mid - 1;
                    }
                } else {
                    if ( *( mid + 1 ) > *i ) {
                        ++mid;
                        T bac = *i;
                        for ( T *p = i; p > mid; --p ) {
                            *p = *( p - 1 );
                        }
                        *mid = bac;
                         break;
                    } else {
                        left = mid + 1;
                    }
                }
            }
        }
     
        return;
     }
}

#endif




相关文章

相关软件