排序算法是面試與工程基礎。本文以 Objective-C 為語言,封裝 Sort 類實現冒泡排序與快速排序,詳細註解分區邏輯、遞歸終止條件、邊界處理,並分析時間複雜度與穩定性差異。
// Sort.h #import@interface Sort : NSObject @property (nonatomic, strong) NSMutableArray* dataSource; - (void)bubbleSort:(NSMutableArray*)dataSource; - (void)quickSort:(NSInteger)start endIndex:(NSInteger)end; @end
// Sort.m - 冒泡排序
- (void)bubbleSort:(NSMutableArray*)dataSource {
NSUInteger count = dataSource.count;
for (NSUInteger i = 0; i < count; ++i) {
for (NSUInteger j = 0; j < count - i - 1; ++j) {
if ([dataSource[j] integerValue] > [dataSource[j+1] integerValue]) {
[dataSource exchangeObjectAtIndex:j withObjectAtIndex:j+1];
}
}
}
// 列印驗證
for (NSUInteger i = 0; i < dataSource.count; ++i) {
NSLog(@"排序--%@", dataSource[i]);
}
}
特性:穩定排序、原地排序、最佳 O(n)(已有序)、最壞/平均 O(n²)、適合小規模/近乎有序數據。
// Sort.m - 快速排序
- (void)quickSort:(NSInteger)start endIndex:(NSInteger)end {
if (start >= end) return; // 遞歸終止:區間長度 ≤ 1
NSInteger pivot = [_dataSource[start] integerValue];
NSInteger left = start, right = end;
NSInteger i = start, j = end;
while (i < j) {
// 從右向左找 < pivot
while (i < j && [_dataSource[j] integerValue] >= pivot) --j;
if (i < j) _dataSource[i++] = _dataSource[j];
// 從左向右找 > pivot
while (i < j && [_dataSource[i] integerValue] <= pivot) ++i;
if (i < j) _dataSource[j--] = _dataSource[i];
}
_dataSource[i] = @(pivot); // 基準值歸位
[self quickSort:left endIndex:i-1]; // 處理左分區
[self quickSort:i+1 endIndex:right]; // 處理右分區
}
| 算法 | 最佳 | 平均 | 最壞 | 空間 | 穩定 | 備註 |
|---|---|---|---|---|---|---|
| 冒泡排序 | O(n) | O(n²) | O(n²) | O(1) | ✓ | 教學/極小數據 |
| 快速排序 | O(n log n) | O(n log n) | O(n²) | O(log n) | ✗ | 通用高效首選 |
NSMutableArray* data = [@[@10, @88, @97, @33, @8, @73, @18] mutableCopy]; Sort* sorter = [[Sort alloc] init]; NSLog(@"=== 冒泡排序 ==="); [sorter bubbleSort:data]; sorter.dataSource = data; // 快排使用實例屬性 NSLog(@"=== 快速排序 ==="); [sorter quickSort:0 endIndex:data.count-1]; for (id obj in data) NSLog(@"最終: %@", obj);
NSComparator 區塊或 SEL,支援任意對象排序start > end 導致單元素區間仍遞歸i <= j 導致越界或死循環NSNumber(陣列存對象)通過封裝 Sort 類,我們將經典算法轉化為可復用、可測試、可擴展的組件,這正是從「寫出算法」到「工程化算法」的關鍵一步。