java数组分离奇数和偶数_以最小的时间复杂度分离偶数和奇数

本文介绍了一种高效算法,用于将数组中的奇数和偶数进行分离,使所有偶数位于数组前部,奇数位于后部。该算法采用双指针技术,仅需一次遍历,实现了O(n)的时间复杂度和O(1)的空间复杂度。
摘要由CSDN通过智能技术生成

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:

算法:

  1. Set two index variable, left = 0 and right = n-1 (n = array length)

    设置两个索引变量, left = 0和right = n-1 ( n =数组长度)

  2. Keep increasing the left index until any odd no is found.

    继续增加左索引,直到找到任何奇数。

  3. Keep decreasing the right index until any even no is found.

    继续减少正确的索引,直到找不到任何索引为止。

  4. 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 


翻译自: https://www.includehelp.com/algorithms/segregate-even-and-odd-numbers-in-minimum-time-complexity.aspx

java数组分离奇数和偶数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值