[英]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.