📌  相关文章
📜  用K对模进行元素排序

📅  最后修改于: 2021-06-25 20:48:59             🧑  作者: Mango

给定一个数组,一个整数的arr []和一个整数K。任务是按照给定数组的元素以K为模的升序对它们进行排序。如果两个数字的余数相同,则较小的数字应排在第一位。

例子

方法:

  • 创建K个空向量。
  • 从左到右遍历数组并更新向量,以使第i向量包含除以K时将i作为余数的元素。
  • 对所有向量分别进行排序,因为使用K给出相同模值的所有元素都必须按升序进行排序。
  • 现在,从第一个向量到最后一个向量,再从向量中的左到右,将按所需的排序顺序提供元素。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
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 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::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> v = new ArrayList<
                                ArrayList>(k);
 
    for(int i = 0; i < k; i++)
        v.add(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++)
    {
        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 prthe
# 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


输出:
12 33 2 6 10 46 3 7

时间复杂度: O(nlogn)

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。