您正在寻找类似于快速排序算法中的“分区”的算法。这个想法是有 2 个索引i
,j
wherei
用于遍历数组,而j
第一个项目的索引大于或等于y
.
在第一个循环之后,您将获得小于y
左侧的数字和右侧的其他数字。但是,您实际上希望将等于的值分组,并且只有右侧y
的数字大于。y
所以我建议在区间 [j,n] 上做同样的事情,但现在当它相等时我也在移动。
// Function to exchange the values of 2 integer variables.
void swap(int *a, int *b) {
int buf = *a;
*a = *b;
*b = buf;
}
// Do the job, in place.
void partition(int *tab, int n, int y) {
// This first part will move every values strictly lesser than y on the left. But the right part could be "6 7 5 8" with y=5. On the right side, numbers are greater or equal to `y`.
int j = 0; // j is the index of the position of the first item greater or equal to y.
int i;
for (i = 0; i < n; i++) {
if (tab[i] < y) {
// We found a number lesser than y, we swap it with the first item that is greater or equal to `y`.
swap(&tab[i], &tab[j]);
j++; // Now the position of the first value greater or equal to y is the next one.
}
}
// Basically the same idea on the right part of the array.
for (i = j; i < n; i++) {
if (tab[i] <= y) {
swap(&tab[i], &tab[j]);
j++;
}
}
}
int main() {
int y;
printf("give integer\n");
scanf("%d", &y);
int x[10] = {5,8,9,4,2,3,2,4,5,6};
partition(x, 10, y);
int i;
for(i=0; i<10; i++)
{
printf("x[%d]=%d\n", i, x[i]);
}
return 0;
}
这段代码给出了x = {5,2,1,6,7,3,2,4,5,6};
和y = 5
:
x[0]=2
x[1]=1
x[2]=3
x[3]=2
x[4]=4
x[5]=5
x[6]=5
x[7]=7
x[8]=6
x[9]=6
前 5 个元素小于 5,其他元素大于或等于 5。