#!/usr/bin/perl use strict; use warnings; use Algorithm::Numerical::Shuffle qw( shuffle ); use Inline C => 'DATA'; my $max = 10; my @values = 1 .. $max; my @values_mixed = shuffle(@values); my @top = topNbs(5, sub { $a <=> $b }, \@values_mixed); print join(" ",sort { $a <=> $b } @top),"\n"; __END__ __C__ int callComp( SV* cmp, GV *first, GV *second, SV *a, SV *b) { int count, rv; dSP; ENTER; SAVETMPS; PUSHMARK(SP); PUTBACK; GvSV(first) = a; GvSV(second) = b; if( ( count = call_sv( cmp, G_SCALAR|G_NOARGS) ) != 1 ) croak( "Bad comparator" ); SPAGAIN; rv = POPi; FREETMPS; LEAVE; } void topNbs( int n, SV *cmp, AV*data) { SV **topN; GV *first, *second; int len = av_len( data ); int i, j, k; int left, right; Inline_Stack_Vars; Newz( 1, topN, n + 1, SV* ); for (i = 0; i < n+1; i++) { topN[i] = newSViv( 0 ); } first = gv_fetchpv("a", TRUE, SVt_PV); second = gv_fetchpv("b", TRUE, SVt_PV); for( i = 0; i <= len; i++ ) { SV *val = av_fetch( data, i, 0 ); int comp = callComp(cmp, first, second, val, topN[ n - 1]); if (comp <= 0) continue; left = 0; right = n - 1; while (left < right) { int middle = (left + right) >> 1; if (callComp(cmp, first, second, val, topN[ n - 1]) <= 0) { left = middle + 1; } else { right = middle; } } if( callComp(cmp, first, second, topN[ left ], val) < 0) { for( k = n; k > left; k-- ) topN[ k ] = topN[ k-1 ]; topN[ left ] = val; } } Inline_Stack_Reset; for( i = 0; i < n; i++ ) Inline_Stack_Push( sv_2mortal( newSVsv( topN[ i ] ) ) ); Safefree( topN ); Inline_Stack_Done; }