Why the Average Complexity of Bucket sort is O(n)?
Part 1: Introduction and Code Bucket Sort is an efficient sorting algorithm when input values are uniformly distributed over a range. It works by distributing elements into different “buckets”, sorting each bucket, and then concatenating the results. Here’s a typical Python implementation where each bucket is sorted with Insertion Sort: def insertion_sort(bucket): for i in range(1, len(bucket)): key = bucket[i] j = i - 1 while j >= 0 and bucket[j] > key: bucket[j + 1] = bucket[j] j -= 1 bucket[j + 1] = key def bucket_sort(arr): n = len(arr) buckets = [[] for _ in range(n)] # Put array elements in different buckets for num in arr: bi = int(n * num) # assuming input numbers are in [0,1) buckets[bi].append(num) # Sort individual buckets using insertion sort for bucket in buckets: insertion_sort(bucket) # Concatenate all buckets into arr[] index = 0 for bucket in buckets: for num in bucket: arr[index] = num index += 1 Why Insertion Sort? Insertion sort is simple and efficient for small or nearly sorted lists. Since each bucket contains only a fraction of the input, sorting each bucket with insertion sort is fast. ...