Sort the character array based on ASCII % N

Given an array arr[] of characters and an integer M, the task is to sort the array based on ASCII % M i.e. the character whose ASCII value % M is minimum should appear first.

Examples:

Input: arr[] = {‘a’, ‘b’, ‘c’, ‘e’}, M = 2
Output: b a c e
The ASCII % M for the array are
{97 % 2, 98 % 2, 99 % 2, 101 % 2} i.e. {1, 0, 1, 1}

Input: arr[] = {‘g’, ‘e’, ‘e’, ‘k’, ‘s’}, M = 8
Output: k s e e g

Method 1: Write a function to sort the array and instead of comparing the values of the characters, compare their ASCII values % M to sort the array. Print the sorted array in the end.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// A utility function to swap two elements
void swap(char* a, char* b)
{
    char t = *a;
    *a = *b;
    *b = t;
}
  
/* This function takes last element as pivot, places 
the pivot element at its correct position in sorted 
    array, and places all smaller (smaller than pivot) 
to left of pivot and all greater elements to right 
of pivot */
int partition(char arr[], int low, int high, int mod)
{
  
    // pivot
    char pivot = arr[high];
  
    // Index of smaller element
    int i = (low - 1);
  
    int piv = pivot % mod;
    for (int j = low; j <= high - 1; j++) {
  
        int a = arr[j] % mod;
        // If current element is smaller than or
        // equal to pivot
        // Instead of values, ASCII % m values
        // are compared
        if (a <= piv) {
  
            // Increment index of smaller element
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}
  
/* The main function that implements QuickSort 
arr[] --> Array to be sorted, 
low --> Starting index, 
high --> Ending index */
void quickSort(char arr[], int low, int high, int mod)
{
    if (low < high) {
        /* pi is partitioning index, arr[p] is now 
        at right place */
        int pi = partition(arr, low, high, mod);
  
        // Separately sort elements before
        // partition and after partition
        quickSort(arr, low, pi - 1, mod);
        quickSort(arr, pi + 1, high, mod);
    }
}
  
// Function to print the given array
void printArray(char arr[], int size)
{
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
}
  
// Driver code
int main()
{
    char arr[] = { 'g', 'e', 'e', 'k', 's' };
    int n = sizeof(arr) / sizeof(arr[0]);
    int mod = 8;
  
    // Sort the given array
    quickSort(arr, 0, n - 1, mod);
  
    // Print the sorted array
    printArray(arr, n);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
class GFG
{
  
    /* This function takes last element as pivot, places 
    the pivot element at its correct position in sorted 
        array, and places all smaller (smaller than pivot) 
    to left of pivot and all greater elements to right 
    of pivot */
    static int partition(char arr[], int low, int high, int mod)
    {
      
        // pivot
        char pivot = arr[high];
      
        // Index of smaller element
        int i = (low - 1);
      
        int piv = pivot % mod;
        for (int j = low; j <= high - 1; j++) 
        {
      
            int a = arr[j] % mod;
              
            // If current element is smaller than or
            // equal to pivot
            // Instead of values, ASCII % m values
            // are compared
            if (a <= piv) 
            {
      
                // Increment index of smaller element
                i++;
                      
                // swap 
                char t = arr[i];
                arr[i] = arr[j];
                arr[j] = t;
      
            }
        }
  
        char t = arr[i+1];
        arr[i+1] = arr[high];
        arr[high] = t;
      
        return (i + 1);
    }
      
    /* The main function that implements QuickSort 
    arr[] --> Array to be sorted, 
    low --> Starting index, 
    high --> Ending index */
    static void quickSort(char arr[], int low, int high, int mod)
    {
        if (low < high) 
        {
            /* pi is partitioning index, arr[p] is now 
            at right place */
            int pi = partition(arr, low, high, mod);
      
            // Separately sort elements before
            // partition and after partition
            quickSort(arr, low, pi - 1, mod);
            quickSort(arr, pi + 1, high, mod);
        }
    }
      
    // Function to print the given array
    static void printArray(char arr[], int size)
    {
        for (int i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
    }
      
    // Driver code
    public static void main(String [] args)
    {
        char arr[] = { 'g', 'e', 'e', 'k', 's' };
        int n = arr.length;
        int mod = 8;
      
        // Sort the given array
        quickSort(arr, 0, n - 1, mod);
      
        // Print the sorted array
        printArray(arr, n);
          
    }
}
  
// This code is contibuted by ihritik

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;
  
class GFG
{
  
    /* This function takes last element as pivot, places 
    the pivot element at its correct position in sorted 
        array, and places all smaller (smaller than pivot) 
    to left of pivot and all greater elements to right 
    of pivot */
    static int partition(char []arr, int low, int high, int mod)
    {
      
        // pivot
        char pivot = arr[high];
      
        // Index of smaller element
        int i = (low - 1);
        char t;
        int piv = pivot % mod;
        for (int j = low; j <= high - 1; j++)
        {
      
            int a = arr[j] % mod;
            // If current element is smaller than o
            // equal to pivot
            // Instead of values, ASCII % m values
            // are compared
            if (a <= piv)
            {
      
                // Increment index of smaller element
                i++;
                      
                // swap 
                t = arr[i];
                arr[i] = arr[j];
                arr[j] = t;
      
            }
        }
  
        t = arr[i+1];
        arr[i+1] = arr[high];
        arr[high] = t;
      
        return (i + 1);
    }
      
    /* The main function that implements QuickSort 
    arr[] --> Array to be sorted, 
    low --> Starting index, 
    high --> Ending index */
    static void quickSort(char []arr, int low, int high, int mod)
    {
        if (low < high)
        {
            /* pi is partitioning index, arr[p] is now 
            at right place */
            int pi = partition(arr, low, high, mod);
      
            // Separately sort elements before
            // partition and after partition
            quickSort(arr, low, pi - 1, mod);
            quickSort(arr, pi + 1, high, mod);
        }
    }
      
    // Function to print the given array
    static void printArray(char []arr, int size)
    {
        for (int i = 0; i < size; i++)
            Console.Write(arr[i] + " ");
    }
      
    // Driver code
    public static void Main()
    {
        char []arr = { 'g', 'e', 'e', 'k', 's' };
        int n = arr.Length;
        int mod = 8;
      
        // Sort the given array
        quickSort(arr, 0, n - 1, mod);
      
        // Print the sorted array
        printArray(arr, n);
          
    }
}
  
// This code is contibuted by ihritik

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the above approach 
  
""" This function takes last element as pivot, 
places the pivot element at its correct position 
in sorted array, and places all smaller  
(smaller than pivot) to left of pivot and 
all greater elements to right of pivot """
def partition(arr, low, high, mod) :
  
    # pivot 
    pivot = ord(arr[high]); 
  
    # Index of smaller element 
    i = (low - 1); 
  
    piv = pivot % mod; 
    for j in range(low, high) : 
  
        a = ord(arr[j]) % mod; 
          
        # If current element is smaller than or 
        # equal to pivot 
        # Instead of values, ASCII % m values 
        # are compared 
        if (a <= piv) :
  
            # Increment index of smaller element 
            i += 1
            arr[i], arr[j] = arr[j], arr[i]
      
    arr[i + 1], arr[high] = arr[high], arr[i + 1
      
    return (i + 1); 
  
""" The main function that implements QuickSort 
arr[] --> Array to be sorted, 
low --> Starting index, 
high --> Ending index """
  
def quickSort(arr, low, high, mod) :
      
    if (low < high) : 
          
        ''' pi is partitioning index, 
        arr[p] is now at right place '''
        pi = partition(arr, low, high, mod); 
  
        # Separately sort elements before 
        # partition and after partition 
        quickSort(arr, low, pi - 1, mod); 
        quickSort(arr, pi + 1, high, mod); 
          
        return arr
  
# Function to print the given array 
def printArray(arr, size) :
      
    for i in range(0, size) :
        print(arr[i], end = " "); 
  
# Driver code 
if __name__ == "__main__"
  
    arr = [ 'g', 'e', 'e', 'k', 's' ]; 
    n = len(arr); 
    mod = 8
  
    # Sort the given array 
    arr = quickSort(arr, 0, n - 1, mod); 
  
    # Print the sorted array 
    printArray(arr, n); 
  
# This code is contributed by AnkitRai01

chevron_right


Output:

k s e e g

Method 2: The sorting can also be done using std::sort() and modifying the comparator.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
int M;
  
// Comparator used to sort the array
// according to ASCII % M
bool comparator(char ch1, char ch2)
{
    int i = ch1 % M;
    int j = ch2 % M;
    return (i < j);
}
  
// Function to print the given array
void printArray(char arr[], int size)
{
    for (int i = 0; i < size; i++)
        cout << arr[i] << " ";
}
  
// Driver code
int main()
{
    char arr[] = { 'g', 'e', 'e', 'k', 's' };
    int n = sizeof(arr) / sizeof(arr[0]);
    M = 8;
  
    // Sort the given array
    sort(arr, arr + n, comparator);
  
    // Print the sorted array
    printArray(arr, n);
  
    return 0;
}

chevron_right


Output:

k s e e g


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : AnkitRai01, ihritik



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.