请参阅以下伪代码以进行就地修补(来自Wikipedia):
function partition(array, left, right, pivotIndex) pivotValue := array[pivotIndex] swap array[pivotIndex] and array[right] // Move pivot to end storeIndex := left for i from left to right - 1 // left ≤ i < rightif array[i] ≤ pivotValue swap array[i] and array[storeIndex] storeIndex := storeIndex + 1 swap array[storeIndex] and array[right] // Move pivot to its final place return storeIndex
注意,它遍历整个数组(最后一个索引除外)。直到最后,透视图才被交换。在您的代码中,关键值在整个循环中不断变化,这似乎是不正确的。
每次进行交换时,交换目标(上面的storeIndex)都应更改。
同样,您只需要交换小于左侧枢轴的值。如果所有低值都在左侧,则高值将最终在右侧。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)