Sort elements by modulo with K
Last Updated :
19 Dec, 2022
Given an array, arr[] of integers and an integer K. The task is to sort the elements of the given array in the increasing order of their modulo with K. If two numbers have the same remainder then the smaller number should come first.
Examples:
Input: arr[] = {10, 3, 2, 6, 12}, K = 4
Output: 12 2 6 10 3
{12, 2, 6, 10, 3} is the required sorted order as the modulo
of these elements with K = 4 is {0, 2, 2, 2, 3}.
Input: arr[] = {3, 4, 5, 10, 11, 1}, K = 3
Output: 3 1 4 10 5 11
Approach:
- Create K empty vectors.
- Traverse the array from left to right and update the vectors such that the ith vector contains the elements that give i as the remainder when divided by K.
- Sort all the vectors separately as all the elements that give the same modulo value with K have to be sorted in ascending.
- Now, starting from the first vector to the last vector and going from left to right in the vectors will give the elements in the required sorted order.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Utility function to print the
// contents of an array
void printArr(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Function to sort the array elements
// based on their modulo with K
void sortWithRemainder(int arr[], int n, int k)
{
// Create K empty vectors
vector<int> v[k];
// Update the vectors such that v[i]
// will contain all the elements
// that give remainder as i
// when divided by k
for (int i = 0; i < n; i++) {
v[arr[i] % k].push_back(arr[i]);
}
// Sorting all the vectors separately
for (int i = 0; i < k; i++)
sort(v[i].begin(), v[i].end());
// Replacing the elements in arr[] with
// the required modulo sorted elements
int j = 0;
for (int i = 0; i < k; i++) {
// Add all the elements of the
// current vector to the array
for (vector<int>::iterator it = v[i].begin();
it != v[i].end(); it++) {
arr[j] = *it;
j++;
}
}
// Print the sorted array
printArr(arr, n);
}
// Driver code
int main()
{
int arr[] = { 10, 7, 2, 6, 12, 3, 33, 46 };
int n = sizeof(arr) / sizeof(arr[0]);
int k = 4;
sortWithRemainder(arr, n, k);
return 0;
}
Java
// Java implementation of the approach
import java.util.*;
class GFG{
// Utility function to print the
// contents of an array
static void printArr(int[] arr, int n)
{
for(int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
// Function to sort the array elements
// based on their modulo with K
static void sortWithRemainder(int[] arr,
int n, int k)
{
// Create K empty vectors
ArrayList<
ArrayList<Integer>> v = new ArrayList<
ArrayList<Integer>>(k);
for(int i = 0; i < k; i++)
v.add(new ArrayList<Integer>());
// Update the vectors such that v[i]
// will contain all the elements
// that give remainder as i
// when divided by k
for(int i = 0; i < n; i++)
{
int t = arr[i] % k;
v.get(t).add(arr[i]);
}
// Sorting all the vectors separately
for(int i = 0; i < k; i++)
{
Collections.sort(v.get(i));
}
// Replacing the elements in
// arr[] with the required
// modulo sorted elements
int j = 0;
for(int i = 0; i < k; i++)
{
// Add all the elements of the
// current vector to the array
for(int x : v.get(i))
{
arr[j] = x;
j++;
}
}
// Print the sorted array
printArr(arr, n);
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 10, 7, 2, 6,
12, 3, 33, 46 };
int n = arr.length;
int k = 4;
sortWithRemainder(arr, n, k);
}
}
// This code is contributed by grand_master
Python3
# Python3 implementation of the approach
# Utility function to print
# contents of an array
def printArr(arr, n):
for i in range(n):
print(arr[i], end = ' ')
# Function to sort the array elements
# based on their modulo with K
def sortWithRemainder(arr, n, k):
# Create K empty vectors
v = [[] for i in range(k)]
# Update the vectors such that v[i]
# will contain all the elements
# that give remainder as i
# when divided by k
for i in range(n):
v[arr[i] % k].append(arr[i])
# Sorting all the vectors separately
for i in range(k):
v[i].sort()
# Replacing the elements in arr[] with
# the required modulo sorted elements
j = 0
for i in range(k):
# Add all the elements of the
# current vector to the array
for it in v[i]:
arr[j] = it
j += 1
# Print the sorted array
printArr(arr, n)
# Driver code
if __name__=='__main__':
arr = [ 10, 7, 2, 6, 12, 3, 33, 46 ]
n = len(arr)
k = 4
sortWithRemainder(arr, n, k)
# This code is contributed by pratham76
C#
// C# implementation of the
// above approach
using System;
using System.Collections;
class GFG{
// Utility function to print the
// contents of an array
static void printArr(int []arr,
int n)
{
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
// Function to sort the array elements
// based on their modulo with K
static void sortWithRemainder(int []arr,
int n, int k)
{
// Create K empty vectors
ArrayList []v = new ArrayList[k];
for(int i = 0; i < k; i++)
{
v[i] = new ArrayList();
}
// Update the vectors such that v[i]
// will contain all the elements
// that give remainder as i
// when divided by k
for (int i = 0; i < n; i++)
{
v[arr[i] % k].Add(arr[i]);
}
// Sorting all the vectors separately
for (int i = 0; i < k; i++)
{
v[i].Sort();
}
// Replacing the elements in
// arr[] with the required
// modulo sorted elements
int j = 0;
for (int i = 0; i < k; i++)
{
// Add all the elements of the
// current vector to the array
foreach(int x in v[i])
{
arr[j] = x;
j++;
}
}
// Print the sorted array
printArr(arr, n);
}
// Driver Code
public static void Main(string[] args)
{
int []arr = {10, 7, 2, 6,
12, 3, 33, 46};
int n = arr.Length;
int k = 4;
sortWithRemainder(arr, n, k);
}
}
// This code is contributed by rutvik_56
JavaScript
<script>
// Javascript implementation of the approach
// Utility function to print the
// contents of an array
function printArr(arr, n)
{
for (let i = 0; i < n; i++)
document.write(arr[i] + " ");
}
// Function to sort the array elements
// based on their modulo with K
function sortWithRemainder(arr, n, k)
{
// Create K empty vectors
let v = new Array();
for (let i = 0; i < k; i++)
{
v.push([])
}
// Update the vectors such that v[i]
// will contain all the elements
// that give remainder as i
// when divided by k
for (let i = 0; i < n; i++) {
v[arr[i] % k].push(arr[i]);
}
// Sorting all the vectors separately
for (let i = 0; i < k; i++)
v[i].sort((a, b) => a - b);
console.log(v)
// Replacing the elements in arr[] with
// the required modulo sorted elements
let j = 0;
for (let i = 0; i < k; i++) {
// Add all the elements of the
// current vector to the array
for (let it of v[i]) {
arr[j] = it;
j++;
}
}
// Print the sorted array
printArr(arr, n);
}
// Driver code
let arr = [10, 7, 2, 6, 12, 3, 33, 46];
let n = arr.length;
let k = 4;
sortWithRemainder(arr, n, k);
// This code is contributed by _saurabh_jaiswal
</script>
Output12 33 2 6 10 46 3 7
Time Complexity: O(nlogn)
Auxiliary Space: O(k), where k is a given integer.
Similar Reads
Sort elements of array whose modulo with K yields P Given an array of integers and a number K. The task is to sort only those elements of the array which yields remainder P upon division by K . Sorting must be done at their relative positions only without affecting any other elements. Examples: Input : arr[] = {10, 3, 2, 6, 12}, K = 4, P = 2 Output :
7 min read
Sort the given stack elements based on their modulo with K Given a stack of integers and an integer K, the task is to sort the elements of the given stack using another stack in the increasing order of their modulo with K. If two numbers have the same remainder then the smaller number should come first.Examples Input: stack = {10, 3, 2, 6, 12}, K = 4 Output
7 min read
Longest subarray with elements having equal modulo K Given an integer K and an array arr of integer elements, the task is to print the length of the longest sub-array such that each element of this sub-array yields same remainder upon division by K. Examples: Input: arr[] = {2, 1, 5, 8, 1}, K = 3 Output: 2 {2, 1, 5, 8, 1} gives remainders {2, 1, 2, 2,
10 min read
Sorting array elements with set bits equal to K Given an array of integers and a number K . The task is to sort only those elements of the array whose total set bits are equal to K. Sorting must be done at their relative positions only without affecting any other elements.Examples: Input : arr[] = {32, 1, 9, 4, 64, 2}, K = 1 Output : 1 2 9 4 32 6
6 min read
Sorting all array elements except one Given an array, a positive integer, sort the array in ascending order such that the element at index K in the unsorted array stays unmoved and all other elements are sorted. Examples: Input : arr[] = {10, 4, 11, 7, 6, 20} k = 2; Output : arr[] = {4, 6, 11, 7, 10, 20} Input : arr[] = {30, 20, 10} k =
6 min read
Finding 'k' such that its modulus with each array element is same Given an array of n integers .We need to find all 'k' such that arr[0] % k = arr[1] % k = ....... = arr[n-1] % k Examples: Input : arr[] = {6, 38, 34}Output : 1 2 4 6%1 = 38%1 = 34%1 = 0 6%2 = 38%2 = 34%2 = 0 6%4 = 38%4 = 34%2 = 2Input : arr[] = {3, 2}Output : 1Suppose the array contains only two el
8 min read
Kâth Smallest Element in Unsorted Array Given an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Examples:Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content[Naive Ap
15 min read
Sort elements by frequency | Set 5 (using Java Map) Given an integer array, sort the array according to the frequency of elements in decreasing order, if the frequency of two elements are same then sort in increasing order Examples: Input: arr[] = {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12} Output: 3 3 3 3 2 2 2 12 12 4 5 Explanation : No. Freq 2 : 3 3 : 4 4
3 min read
Sort elements of the array that occurs in between multiples of K Given an array arr[] and an integer K. The task is to sort the elements that are in between any two multiples of K. Examples: Input: arr[] = {2, 1, 13, 3, 7, 8, 21, 13, 12}, K = 2 Output: 2 1 3 7 13 8 13 21 12 The multiples of 2 in the array are 2, 8 and 12. The elements that are in between the firs
6 min read
Find k smallest elements in an array Given an array arr[] and an integer k, the task is to find k smallest elements in the given array. Elements in the output array can be in any order.Examples:Input: arr[] = [1, 23, 12, 9, 30, 2, 50], k = 3Output: [1, 2, 9]Input: arr[] = [11, 5, 12, 9, 44, 17, 2], k = 2Output: [2, 5]Table of Content[A
15 min read