码迷,mamicode.com
首页 > 其他好文 > 详细

Algorithms: Design and Analysis, Part 1 【program 2/统计快排比较次数】

时间:2015-10-24 15:47:43      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

#include<string>
#include <vector>
#include <fstream>

using namespace std;

std::vector<int> v;
int bigArr[10000];
int helpArr[10000];

int partition( int* arr, int left, int right );

int QSort( int* arr, int left, int right )
{
    if( left >= right )
    {
        return 0;
    }

    int partionIdx = partition( arr, left, right );

    int leftCmpNum = QSort( arr,left, partionIdx - 1 );
    int rightCmpNum = QSort( arr, partionIdx + 1, right );
    
    return ( right - left ) + leftCmpNum + rightCmpNum;
}

int partition( int* arr, int left, int right )
{
    if( left >= right )
    {
        return left;
    }

    int key = arr[left];

    int lastLessIdx = left;
    int idx = left + 1;

    while( idx <= right )
    {
        if( arr[idx] < key )
        {
            int tmp = arr[idx];

            lastLessIdx++;
            arr[idx] = arr[lastLessIdx];
            arr[lastLessIdx] = tmp;
        }

        idx++;
    }

    int tmp = arr[lastLessIdx];
    arr[lastLessIdx] = arr[left]; 
    arr[left] = tmp;

    return lastLessIdx;
}

void main()
{
    fstream infile( "QuickSort.txt" );
    string tmp;
    while( getline( infile, tmp ) )
    {
        int num = atoi( tmp.c_str() );
        v.push_back( num );
    }

    for( int i = 0; i < 10000; i++ )
    {
        bigArr[i] = v.at(i);
    }

    int cmpNum = QSort( bigArr, 0, 9999 );
}

 

Algorithms: Design and Analysis, Part 1 【program 2/统计快排比较次数】

标签:

原文地址:http://www.cnblogs.com/yxfu/p/4906900.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!