C++ 分离奇偶数数组
我已经实现了一个算法来更改数组,以便将所有偶数移到数组的开头,将旧数移到数组的结尾。这是我的节目:-C++ 分离奇偶数数组,c++,arrays,algorithm,C++,Arrays,Algorithm,我已经实现了一个算法来更改数组,以便将所有偶数移到数组的开头,将旧数移到数组的结尾。这是我的节目:- #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
#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: 只有当
l
未跨越h
时,您才需要调用交换
,您总是在调用它
考虑数组{2,1}
,它已经被设置了。现在,在两个内部while循环之后,
l
将是1
,h
将是0
。在您的情况下,您将继续进行交换,但实际上不需要交换,因为l
已跨越h
。
当这种情况发生时,阵列已经被隔离
所以改变
swap(arr[l], arr[h]);
到
这是不正确的。考虑一个数组<代码> {2,4},现在在上面的某个点,while循环<代码> L>代码>将是<代码> 2代码>,然后继续访问<代码> ARR(2)< /代码>,不存在。
您需要的是:
while(l is a valid index AND number at index l is even) {
l++;
}
你就不能用标准排序吗 比如:
#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);
#包括
#包括
int值[]={40,10,100,90,20,25};
整数比较(常数无效*a,常数无效*b)
{
//返回-1 a偶数和b奇数
//0均为偶数或均为奇数
//1 b-偶和a-奇
}
qsort(值,6,sizeof(int),比较);
您尝试执行的操作也称为分区。标准库提供了两种算法来实现这一点: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
}
如果您仍然对,'s对std::partition
的描述感兴趣,则包含等效代码。您的版本在交换之前缺少
if
语句。只有当左边有一个奇数时,才应该进行交换。尽可能简单:
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++;
}
}
}
void partitionEvenOdd(int数组[],int数组长度,int&firstOdd)
{
第一奇数=0;
对于(int i=0;i
建议:使用sizeof(arr)
查找数组的size
。请注意sizeof(arr)
返回数组的大小(以字节为单位,而不是以元素为单位)。使用sizeof(arr)/sizeof(*arr)
获取元素的数量。除非qsort()
进行三向分区,否则您将在时间上浪费一个日志因子。但是它易于理解和维护。根据阵列的大小,这实际上可能并不重要。是的,“可维护性”和易于使用是我的第一个目标。就性能而言,对于小型阵列来说应该是一样的,作者并没有提到大小。
#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);
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
}
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++;
}
}
}