Objective C 中的桶排序实现
Bucket Sort implementation in Objective C
我一直在 Objective-C 中实现不同的排序算法(快速排序、归并排序、冒泡排序)。但是我还没有找到桶排序算法的明确实现
我正在尝试在 objective C 中找到桶排序算法的简单有效的实现。
最后我自己做了,如果有人需要的话,这是我的实现:
- (NSArray*)bucketSort:(NSArray<NSNumber*> *)array buckets:(NSInteger)k {
// Initialize array of buckets
NSMutableArray<NSMutableArray*> *buckets = [NSMutableArray arrayWithCapacity:k];
for (int i=0; i < buckets.count; i++)
buckets[i] = [NSMutableArray new];
// Add elements to buckets
for (int i=0; i < buckets.count; i++) {
NSInteger index = k * array[i].floatValue; // Asuming "array" has values between 0 and 1
if (index < buckets.count) [buckets[index] addObject:array[i]];
}
NSMutableArray *sortedArray = [NSMutableArray new];
// Sort individual buckets
// Concatenate all sorted buckets in order
for (int i=0; i < buckets.count; i++) {
buckets[i] = [self quickSort:buckets[i]]; // Sorting algorithm like quicksort/mergesort/insertionsort
[sortedArray addObjectsFromArray:buckets[i]];
}
return sortedArray;
}
我一直在 Objective-C 中实现不同的排序算法(快速排序、归并排序、冒泡排序)。但是我还没有找到桶排序算法的明确实现
我正在尝试在 objective C 中找到桶排序算法的简单有效的实现。
最后我自己做了,如果有人需要的话,这是我的实现:
- (NSArray*)bucketSort:(NSArray<NSNumber*> *)array buckets:(NSInteger)k {
// Initialize array of buckets
NSMutableArray<NSMutableArray*> *buckets = [NSMutableArray arrayWithCapacity:k];
for (int i=0; i < buckets.count; i++)
buckets[i] = [NSMutableArray new];
// Add elements to buckets
for (int i=0; i < buckets.count; i++) {
NSInteger index = k * array[i].floatValue; // Asuming "array" has values between 0 and 1
if (index < buckets.count) [buckets[index] addObject:array[i]];
}
NSMutableArray *sortedArray = [NSMutableArray new];
// Sort individual buckets
// Concatenate all sorted buckets in order
for (int i=0; i < buckets.count; i++) {
buckets[i] = [self quickSort:buckets[i]]; // Sorting algorithm like quicksort/mergesort/insertionsort
[sortedArray addObjectsFromArray:buckets[i]];
}
return sortedArray;
}