java桶排序python
时间: 2023-12-19 18:32:23 浏览: 132
以下是Java和Python实现桶排序的例子:
1. Java实现桶排序
```java
import java.util.Arrays;
public class BucketSort {
public static void bucketSort(int[] array, int bucketSize) {
if (array.length == 0) {
return;
}
int minValue = array[0];
int maxValue = array[0];
for (int value : array) {
if (value < minValue) {
minValue = value;
} else if (value > maxValue) {
maxValue = value;
}
}
int bucketCount = (maxValue - minValue) / bucketSize + 1;
int[][] buckets = new int[bucketCount][0];
for (int value : array) {
int bucketIndex = (value - minValue) / bucketSize;
buckets[bucketIndex] = grow(buckets[bucketIndex], value);
}
int currentIndex = 0;
for (int[] bucket : buckets) {
InsertionSort.insertionSort(bucket);
for (int value : bucket) {
array[currentIndex++] = value;
}
}
}
private static int[] grow(int[] array, int value) {
array = Arrays.copyOf(array, array.length + 1);
array[array.length - 1] = value;
return array;
}
public static void main(String[] args) {
int[] array = {29, 25, 3, 49, 9, 37, 21, 43};
bucketSort(array, 10);
System.out.println("Sorted array: " + Arrays.toString(array));
}
}
class InsertionSort {
public static void insertionSort(int[] array) {
for (int i = 1; i < array.length; i++) {
int current = array[i];
int j = i - 1;
while (j >= 0 && array[j] > current) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = current;
}
}
}
```
2. Python实现桶排序
```python
def bucket_sort(array, bucketSize):
if len(array) == 0:
return array
minValue = array[0]
maxValue = array[0]
for value in array:
if value < minValue:
minValue = value
elif value > maxValue:
maxValue = value
bucketCount = (maxValue - minValue) // bucketSize + 1
buckets = [[] for _ in range(bucketCount)]
for value in array:
bucketIndex = (value - minValue) // bucketSize
buckets[bucketIndex].append(value)
array.clear()
for bucket in buckets:
bucket.sort()
array.extend(bucket)
return array
array = [29, 25, 3, 49, 9, 37, 21, 43]
bucket_sort(array, 10)
print("Sorted array:", array)
```
阅读全文