[英]Segregating an array for even and odd numbers
我已经实现了一种算法来更改数组,以便所有偶数都移到数组的开头,旧数字移到数组的结尾。 这是我的程序:
#include <iostream>
using namespace std;
void print(int arr[], int size) {
for(int i=0;i<size;i++) {
cout<<arr[i]<<" ";
}
cout<<endl;
}
void segregate(int arr[], int size) {
int l=0, h=size-1;
while(l<h) {
while(!(arr[l]%2) && l<size) {
l++;
}
while((arr[h]%2) && h >=0) {
h--;
}
swap(arr[l], arr[h]);
}
}
int main() {
int arr[] = {1,2,3,4,5,6,7,8,9};
int size = 9;
print(arr,size);
segregate(arr,size);
print(arr,size);
return 0;
}
我没有得到预期的结果
1 2 3 4 5 6 7 8 9
8 2 6 5 4 3 7 1 9
我想念什么?
您尝试执行的操作也称为分区。 标准库提供了两种算法来做到这一点: std::partition
和std::stable_partition
。
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9};
auto split = std::partition( std::begin(arr), std::end( arr ),
[]( int a ) { return ! a%2; } );
// [ begin, split ) are all even
// [ split, end ) are all odd
}
如果您仍然对编写自己的内容感兴趣,则cppreference的std::partition
描述std::partition
包含等效的代码。
您的版本在交换之前丢失了if
语句。 仅当左边有奇数时,才应交换。
问题一:
仅当l
尚未超过h
,才需要调用swap
,而您总是在调用它。
考虑数组{2,1}
,它已经被隔离了。
现在,在两个内部while循环之后, l
将为1
, h
将为0
。 在您的情况下,您将继续进行交换,但是实际上不需要交换,因为l
超过了h
。 当发生这种情况时,阵列已经被隔离。
所以改变
swap(arr[l], arr[h]);
至
if(l<h) {
swap(arr[l], arr[h]);
}
问题2:
同样,内部while循环中条件的顺序也必须颠倒。 您正在检查
while(number at index l is even AND l is a valid index) {
l++;
}
这是不正确的。 考虑一个数组{2,4}
,现在在上面的某个时刻,而循环l
将为2
,然后继续访问arr[2]
,该数组不存在。
您需要的是:
while(l is a valid index AND number at index l is even) {
l++;
}
变得如此简单:
void partitionEvenOdd(int array[], int arrayLength, int &firstOdd)
{
firstOdd = 0;
for (int i = 0; i < arrayLength; i++) {
if (array[i]%2 == 0) {
swap(array[firstOdd], array[i]);
firstOdd++;
}
}
}
您不能只使用标准排序吗?
就像是:
#include <stdio.h>
#include <stdlib.h>
int values[] = { 40, 10, 100, 90, 20, 25 };
int compare (const void * a, const void * b)
{
// return -1 a-even and b-odd
// 0 both even or both odd
// 1 b-even and a-odd
}
qsort (values, 6, sizeof(int), compare);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.