クイックソート アルゴリズムのように、「パーティション」に似たアルゴリズムを探しています。アイデアは、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 以上です。