如題:實(shí)現(xiàn)要求,空間復(fù)雜度為o(1).
如果沒(méi)有這個(gè)要求的話,這個(gè)題目相信很多人都會(huì)手到擒來(lái)。
思路:既然空間復(fù)雜度為o(1),那就得充分利用數(shù)組自己的空間,在數(shù)組內(nèi)部進(jìn)行元素的交換來(lái)達(dá)到目的,思路與快速排序類似,從左邊找到偶數(shù),再?gòu)挠疫呎业狡鏀?shù),進(jìn)行交換,直到左右相遇。
上代碼:
void sort(int nums[], int count) {
if (count == 0) {
return;
}
int s = 0, e = count - 1;
while (s < e) {
while (nums[s] % 2 != 0 && s < e) {
s ++;
}
while (nums[e] % 2 == 0 && s < e) {
e --;
}
if (s == e) {
return;
}
int tem = nums[s];
nums[s] = nums[e];
nums[e] = tem;
}
}