- (void)quickSortArray:(NSMutableArray *)array withLeftIndex:(NSInteger)leftIndex andRightIndex:(NSInteger)rightIndex { if (leftIndex >= rightIndex) {//如果數組長度為0或1時返回 return ; } NSInteger i = leftIndex; NSInteger j = rightIndex; //記錄比較基准數 NSInteger key = [array[i] integerValue]; while (i < j) { /**** 首先從右邊j開始查找比基准數小的值 ***/ while (i < j && [array[j] integerValue] >= key) {//如果比基准數大,繼續查找 j--; } //如果比基准數小,則將查找到的小值調換到i的位置 array[i] = array[j]; /**** 當在右邊查找到一個比基准數小的值時,就從i開始往后找比基准數大的值 ***/ while (i < j && [array[i] integerValue] <= key) {//如果比基准數小,繼續查找 i++; } //如果比基准數大,則將查找到的大值調換到j的位置 array[j] = array[i]; } //將基准數放到正確位置 array[i] = @(key); /**** 遞歸排序 ***/ //排序基准數左邊的 [self quickSortArray:array withLeftIndex:leftIndex andRightIndex:i - 1]; //排序基准數右邊的 [self quickSortArray:array withLeftIndex:i + 1 andRightIndex:rightIndex]; }
