简体   繁体   中英

Most efficient way to sort a unique, bounded array?

I assume this is a duplicate but I couldn't find one.

Let's say we have an array where we know every single value will be unique, and every value will be between a range. For example, let's say we know the array consists of unique values between 0 and 100. Example:

[ 5, 46, 15, 83, 55, 28 ]

I would like to then sort this array into the following:

[ 5, 15, 28, 46, 55, 83 ]

Obviously I could just use Quicksort or any other comparative sort, but that would be O(n log n) . Non-comparative sorts exist as well, such as Radix Sort, Bucket Sort, Counting Sort, etc. but none of those also maintain the constraint that values must be unique, as far as I know.

Generally it is the case that the more constraints you allow, the more efficient your algorithm can become. Are there any algorithms which are even more efficient for unique, bounded arrays? If not, which of the non-comparative sorting algorithms would be most efficient for this type of dataset?

Given the constraint of unique values and a restricted range, you can declare an array whose length is enough to hold every unique integer in the given range, then you can perform a special-case bucket sort where each bucket is always able to contain a unique value, and finally filter the array to remove the leftover empty slots. Like other non-comparative sorting algorithms, this approach is O(n) asymptotic time-complexity.

 const input = [5, 46, 15, 83, 55, 28]; function sort(unsorted, lower, upper) { const sorted = Array(upper - lower); for (let i = 0; i < unsorted.length; ++i) { sorted[unsorted[i] - lower] = unsorted[i]; } return sorted.filter(() => true); } const output = sort(input, 0, 100); console.log(output);

something like that?

 const arr1 = [ 5, 46, 15, 83, 55, 28 ] const min = Math.min(...arr1) const res = [] for(let v of arr1) res[v-min] = v for(let i=res.length;i--;) if (res[i]===undefined) res.splice(i, 1) console.log( res )
 .as-console-wrapper { max-height: 100%;important: top; 0; }

I would suggest a counting sort, but one using an array of bytes for what would normally be the counts, since the count values will only be 0 or 1 since the array to be sorted has unique values. This would also work for an array where no value occurs more than 255 times (so that each count would still fit in an unsigned byte).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM