本文共 1177 字,大约阅读时间需要 3 分钟。
循环排序(Cycle Sort)是一种原地排序算法,适用于需要最小写入次数的场景。它的时间复杂度为O(n²),但每个元素最多只写入一次,因此在某些情况下非常高效。
#importvoid cycleSort(NSMutableArray *array) { NSInteger n = array.count; if (n == 0) { return; } NSInteger currentIndex = 0; while (currentIndex < n) { // 寻找当前元素的正确位置 NSInteger targetIndex = n; boolean found = false; for (NSInteger i = currentIndex; i < n; i++) { if (array[i] < array[i]) { targetIndex = i; found = true; } } if (!found) { break; } // 交换当前元素和目标元素的位置 [array exchangeObjectAtIndex:currentIndex withObjectAtIndex:targetIndex]; currentIndex = targetIndex + 1; }}
初始化:首先检查数组是否为空。如果为空,直接返回。然后初始化currentIndex为0,用于跟踪当前元素的位置。
外部循环:从currentIndex开始,遍历数组,直到遍历完整个数组。
寻找目标位置:在内部循环中,寻找当前元素应该放在的位置targetIndex。初始时,targetIndex设为数组的长度,表示当前元素应该放在数组末尾。然后从currentIndex开始遍历数组,找到第一个小于当前元素的元素的位置,并记录下来。
检查元素位置:如果在内部循环中没有找到目标元素(即found仍为false),说明当前元素已经在正确的位置,提前终止循环。
交换元素:如果找到目标位置,交换当前元素和目标元素的位置,并将currentIndex设为targetIndex + 1,继续外部循环。
终止条件:当整个数组遍历完毕,没有元素需要移动时,循环终止。
通过这种方式,循环排序算法能够高效地将数组排序,确保每个元素最多只被写入一次。
转载地址:http://hjnfk.baihongyu.com/