对数组中的所有偶数进行排序,而不改变奇数元素的顺序
给定一个大小为N的数组arr[] ,任务是对数组中的所有偶数进行排序,而不改变奇数元素的顺序
例子:
Input: arr[] = {4, 7, 2, 11, 15}
Output: {2, 7, 4, 11, 15}
Explanation: Even numbers are sorted at their corresponding places, without changing the order of odd elements
Input: arr[] = {12, 6}
Output: {6, 12}
方法:可以通过将偶数元素分离到另一个容器中来解决该任务,例如“偶数”,对该容器进行排序,并在迭代数组时,将偶数元素替换为存储在偶数中的已排序偶数元素
下面是上述方法的实现:
C++
#include
using namespace std;
// Function to get the required array
void solve(int arr[], int n)
{
// Store even elements
vector evens;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
evens.push_back(arr[i]);
}
// Sort all even elements
sort(evens.begin(), evens.end());
int l = 0;
// Placing even elements in sorted order
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
arr[i] = evens[l++];
}
// Updated array
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Driver Code
int main()
{
int N = 5;
int arr[N] = { 4, 7, 2, 11, 15 };
solve(arr, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
public class GFG {
// Function to get the required array
static void solve(int []arr, int n)
{
// Store even elements
ArrayList evens = new ArrayList();
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
evens.add(arr[i]);
}
// Sort all even elements
Collections.sort(evens);
int l = 0;
// Placing even elements in sorted order
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
arr[i] = evens.get(l++);
}
// Updated array
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
// Driver function
public static void main(String []args)
{
int N = 5;
int []arr = { 4, 7, 2, 11, 15 };
solve(arr, N);
}
}
// This code is contributed by AnkThon
Python3
# python program of the above approach
# Function to get the required array
def solve(arr, n):
# Store even elements
evens = []
for i in range(0, n):
if (arr[i] % 2 == 0):
evens.append(arr[i])
# Sort all even elements
evens.sort()
l = 0
# Placing even elements in sorted order
for i in range(0, n):
if (arr[i] % 2 == 0):
arr[i] = evens[l]
l += 1
# Updated array
for i in range(0, n):
print(arr[i], end=" ")
# Driver Code
if __name__ == "__main__":
N = 5
arr = [4, 7, 2, 11, 15]
solve(arr, N)
# This code is contributed by rakeshsahni
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
// Function to get the required array
static void solve(int []arr, int n)
{
// Store even elements
List evens = new List();
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
evens.Add(arr[i]);
}
// Sort all even elements
evens.Sort();
int l = 0;
// Placing even elements in sorted order
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0)
arr[i] = evens[l++];
}
// Updated array
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
// Driver function
public static void Main()
{
int N = 5;
int []arr = new int[] { 4, 7, 2, 11, 15 };
solve(arr, N);
}
}
// This code is contributed by Samim Hossain Mondal
Javascript
输出
2 7 4 11 15
时间复杂度:O(NlogN)
辅助空间:O(N)