From ddbbf0ea4950dbd7f84c35dfe06d443bab260045 Mon Sep 17 00:00:00 2001 From: Anna Schumaker Date: Sun, 26 Jan 2014 10:41:13 -0500 Subject: [PATCH] playqueue: Improve insertion sort with a binary search My test was done with a library size of 8040. Before this patch, I make 21919628 calls to my "less_than" function. With this patch, I now make 101205 calls to my "less than" function. This comes out to a 216-X improvement. I should have done this sooner. Signed-off-by: Anna Schumaker --- lib/playqueue.cpp | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/lib/playqueue.cpp b/lib/playqueue.cpp index 1a9cac1f..71481a21 100644 --- a/lib/playqueue.cpp +++ b/lib/playqueue.cpp @@ -118,16 +118,27 @@ static bool track_less_than(library :: Song &lhs, library :: Song &rhs) unsigned int Playqueue :: add_sorted(unsigned int track_id, library :: Song &rhs) { - unsigned int id; library :: Song lhs; + unsigned int cur, start = 0, end = (tracks.size() - 1); - for (id = 0; id != tracks.size(); id++) { - library :: lookup(tracks[id], &lhs); - if (!track_less_than(lhs, rhs)) - break; + if (tracks.size() == 0) { + tracks.push_back(track_id); + return 0; } - tracks.insert(tracks.begin() + id, track_id); - return id; + + while (start != end) { + cur = start + ((end - start) / 2); + library :: lookup(tracks[cur], &lhs); + if (track_less_than(lhs, rhs)) { + if (end - start == 1) + cur = end; + start = cur; + } else + end = cur; + } + + tracks.insert(tracks.begin() + cur, track_id); + return cur; } unsigned int Playqueue :: add(unsigned int track_id)