c - 对数组进行分区
问题描述
给定一个包含 n 个元素的随机排序数组 (arr),函数 partitionArray(int arr[], int n, int x) 将元素划分为两个子集,使得元素 <= x 在左侧子集中,元素 > x 在右侧子集。
测试用例的第一行将包含两个数字 n(列表中的元素数)和 x(用于分区的数字),以空格分隔。下一行将包含 N 个空格分隔的整数。
对于某些情况,我从以下函数中得到错误的输出。
这是我的代码:
void partitionArray(int arr[], int n, int x)
{
int i, j, temp;
i = 0;
j = n-1;
while (i < j)
{
while (arr[i] <=x)
i++;
while (arr[j] > x)
j--;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
对于我得到正确输出的情况是:
10 6
28 26 25 5 6 7 24 29 6 10
对于我没有得到正确输出的情况是:
10 17
28 26 25 11 16 12 24 29 6 10
The output I am getting in this:
10
6
12
11
25
16
24
29
26
28
Expected Output:
10
6
12
11
16
25
24
29
26
28
10 6
28 26 25 11 5 7 24 29 6 10
The output I am getting in this:
6
25
5
11
26
7
24
29
28
10
Expected Output:
6
5
25
11
26
7
24
29
28
10
谁能帮我这个
解决方案
下面的变化会做:
if(i < j){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
当 j 的值为 i+1 和arr[i]<x
and时进行交换时,在 while 循环arr[j]>x
之后i++
和之后j--
,代码中 j 的值为 i-1。因此i<j
,在交换之前检查很重要。
假设输入是
2 5
1 10
你的输出将是
10 1
并且必须检查索引,因为索引可能会超出数组的大小。
while (i<n && arr[i]<=x)
i++;
while (j>=0 && arr[j]>x)
j--;
示例输入:
5 7
5 3 2 4 1
5 3
7 6 9 5 6
推荐阅读
- cmake - 我怎么能再次运行cmake?
- python - 如何使用瓶中闪光灯?
- javascript - 如何测试浏览器是否支持 loading='lazy'?
- android - 是否可以在构造函数中将 ViewModel 传递给 Fragment?
- c++ - 为什么 temp 和 c 可以使用点运算符访问 a 和 b 私有变量?
- python - 尝试安装 Python 3 包 RPi.GPIO
- mysql - 数组列中的值 - MySQL
- javascript - 有办法让 CSS-root 获得 JavaScript 值吗?作为默认值
- c - CS50 潮人;如果 lock_pairs 创建循环,则跳过最后一个对
- icons - PWA 主屏幕图标在三星互联网浏览器上呈现模糊