java数组分离奇数和偶数
Problem statement:
问题陈述:
Given an array of integers. Write a function to segregate the Even and Odd numbers. Put the even numbers first.
给定一个整数数组。 编写一个函数来分隔偶数和奇数 。 将偶数放在第一位。
Solution:
解:
Algorithm:
算法:
Set two index variable, left = 0 and right = n-1 (n = array length)
设置两个索引变量, left = 0和right = n-1 ( n =数组长度)
Keep increasing the left index until any odd no is found.
继续增加左索引,直到找到任何奇数。
Keep decreasing the right index until any even no is found.
继续减少正确的索引,直到找不到任何索引为止。
If left < right, swap array[left] and array[right].
如果left <right ,则交换array [left]和array [right] 。
Time complexity: O(n) (only one scan )
时间复杂度: O(n) (仅一次扫描)
Space complexity: O(1) (no additional space used)
空间复杂度: O(1) (不使用其他空间)
Comment: The input order can be changed in the output as we are swapping on local observation.
注释:当我们交换本地观测值时,可以在输出中更改输入顺序。
C ++实现以最小的时间复杂度分离偶数和奇数 (C++ implementation to Segregate even and odd numbers in minimum time complexity)
#include <bits/stdc++.h>
using namespace std;
void print(int* a,int n){
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
void swap(int* a,int* b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
void separate(int* a, int n){
int left=0,right=n-1;
while(left<right){
// increment left until any odd no is found
while(a[left]%2==0 && left<right)
left++;
// increment right until any even no is found
while(a[right]%2==1 && left<right)
right--;
if(left<right){
//swap array[left] & array[left] using pointer to reference
swap(&a[left],&a[right]);
left++;
right--;
}
}
}
int main(){
int n;
// enter array length
cout<<"enter no of elements\n";
cin>>n;
int* a=(int*)(malloc(sizeof(int)*n));
//fill the array
cout<<"enter elements...\n";
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
cout<<"array before segregating...\n";
print(a,n);
cout<<"array after segregating...\n";
separate(a,n);
print(a,n);
return 0;
}
Output
输出量
enter no of elements
8
enter elements...
11
12
13
67
66
45
34
38
array before segregating...
11 12 13 67 66 45 34 38
array after segregating...
38 12 34 66 67 45 13 11
java数组分离奇数和偶数