[Sorting Algorithm] Bucket Sort

Reference: " Comic Algorithm - Xiao Hui's Algorithmic Journey"

Table of contents

1. What is bucket sort

Second, the working principle of bucket sorting

3. Code

4. Time complexity and space complexity


1. What is bucket sort

Bucket sort is a linear time sorting algorithm that is similar to the statistical array created by radix sort. Bucket sorting requires the creation of several buckets to assist in sorting.

A bucket in bucket sorting represents an interval range, which can hold one or more elements.

Second, the working principle of bucket sorting

Suppose there is a non-integer sequence as follows: 4.5, 0.84, 3.25, 2.18, 0.

Step 1: Create buckets and determine the range of each bucket.

There are many different ways how many buckets need to be created and how to determine the range of buckets. The number of buckets created here is equal to the number of elements in the original sequence, except that the last bucket only contains the maximum value of one sequence, and the intervals of the previous buckets are determined in proportion:

Interval span = (maximum value - minimum value) / (number of buckets - 1)

Step 2: To facilitate the original sequence, put the elements into each bucket according to their numbers.

 Step 3: Sort the elements in each bucket separately.

 Step 4: Traverse all buckets and output all elements.

0.5,0.84,2.18,3.25,4.5

3. Code

4. Time complexity and space complexity

Assuming that the original array has n elements, it is divided into n buckets.

Let's analyze the complexity of the algorithm step by step.

The first step is to find the maximum value and minimum value of the sequence, and the operation amount is n.

Step 2, create an empty bucket, and the calculation amount is n.

In the third step, the elements of the original array are allocated to each bucket, and the operation amount is n.

Step 4: Sorting is performed inside each bucket. When the distribution of elements is relatively uniform, the sum of operations of all buckets is n.

Step 5, output the sorted sequence, and the operation amount is n.

Therefore, the overall time complexity of bucket sort is O(n).

As for the space complexity, it is easy to get, and it is also O(n).

Guess you like

Origin blog.csdn.net/weixin_45922730/article/details/130388298