Posts

Showing posts with the label Sorting

400x Sorting Speedup By Switching A.localeCompare(b) To (ab?1:0))

Answer : A great performance improvement can be obtained by declaring the collator object beforehand and using it's compare method. EG: const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' }); arrayOfObjects.sort((a, b) => { return collator.compare(a.name, b.name); }); Here's a benchmark script comparing the 3 methods: const arr = []; for (let i = 0; i < 2000; i++) { arr.push(`test-${Math.random()}`); } const arr1 = arr.slice(); const arr2 = arr.slice(); const arr3 = arr.slice(); console.time('#1 - localeCompare'); arr1.sort((a, b) => a.localeCompare( b, undefined, { numeric: true, sensitivity: 'base' } )); console.timeEnd('#1 - localeCompare'); console.time('#2 - collator'); const collator = new Intl.Collator('en', { numeric: true, sensitivity: 'base' }); arr2.sort((a, b) => collator.compare(a, b)); console.timeEnd('#2 - collator'); con...

Alphabetical Sorting Of A Sequence Of Names

Image
Answer : Bubble sorter, which I adapt from my modification to David's answer to my question at Trying to eliminate stack overflow during recursion. The \sortlist macro is the bubble sorter (from the referenced answer, but with and rather than , as the list seperator). However, it leaves the result in the form of Last Name, First and ... . I had to add the \rework macro to make it First Last Name and employ \whichsep to choose whether a , or and should be inserted between names, depending on their placement in the list. No packages required! \documentclass[10pt]{article} \newcommand\alphabubblesort[1]{\def\sortedlist{}% \expandafter\sortlist#1 and \cr and \relax \expandafter\rework\sortedlist and \relax} \def\sortlist#1and #2and #3\relax{% \let\next\relax \ifx\cr#2\relax% \edef\sortedlist{\sortedlist#1}% \else \picknext#1!and #2!\relax% \if F\flipflop% \edef\sortedlist{\sortedlist#1and }% \def\next{\sortlist#2and #3\relax}% \else...

Conditional Sorting In ElasticSearch

Answer : Yes this is possible in ElasticSearch using a script, either for sorting or for scoring. My preference would be for a scoring script because 'script based score' is going to be quicker (according to the documentation). Using a scoring script, you could use the Unix timestamp for the date field of type int/long and an mvel sorting script in the custom_score query. You might need to re-index your documents. You would also need to be able to convert the searched for time into a Unix timestamp to pump it at ElasticSearch. The sorting script would then deduct the requested timestamp from each document's timestamp and make an absolute value. Then the results are sorted in ascending order - the lowest 'distance' is the best. So when looking for documents dated about a year ago, it would look something like: "query": { "custom_score" : { "query" : { .... }, "params" : { ...