我无法为设置的输入创建分区。我尝试了两件事,第一件事已被注释掉,这只是分区算法的一些基本伪代码,第二件事是我从类说明中解释的内容。首先,主要功能还不错,那就是给我们的。我只需要完成对分区函数的编码。分区功能中注释的所有内容都是我的第一次尝试,未注释的所有内容都是我的第二次尝试。
以下是我们应该测试的一些输入以及正确的结果:
2 6 8 4 1 7枢轴为8;右侧部分为空
int partition(int a[], int first, int last) {
/* int pivot = a[last / 2];
//cout << pivot << endl;
int i = (first - 1);
for (int j = first; j <= last; j++) {
if (a[j] < pivot) {
i++;
//cout << pivot << endl << i << endl << j << endl;
swap(a[i], a[j]);
}
}
cout << pivot << endl << i << endl << first << endl << last << endl;
//swap(a[i + 1], a[last]);
return (i + 1);
}*/
swap(a[first],a[(first+last)/2]);
int pivot = a[first];
int i = a[first];
int j = a[last];
while (i <= j)
{
if (pivot > a[i])
{i++;}
if (pivot < a[j])
{j--;}
if (i <= j)
{swap(a[i],a[j]);}
}
swap(pivot, a[j]);
return i;
}
int main()
{
int x; // number of elements
int nums[10];
cout << "How many elements would you like to enter into the array? (must
be less than 10): ";
cin >> x;
cout << "Enter the elements one per line" << endl;
for (int i = 0; i < x; i++)
{ cin >> nums[i]; }
int pivot_index = partition(nums, 0, x-1);
cout << "The array was partitioned" << endl;
// display up to the pivot without endl
for (int i = 0; i < pivot_index; i++)
cout << nums[i] << " ";
// display the pivot
cout << "| " << nums[pivot_index] << " | " ;
// display from the pivot without endl
for (int i = pivot_index+1; i < x; i++)
cout << nums[i] << " ";
cout << endl;
}