Sort the character array based on ASCII % N

08 Oct, 2021
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++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // A utility function to swap two elementsvoid swap(char* a, char* b){    char t = *a;    *a = *b;    *b = t;} /* This function takes last element as pivot, placesthe 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 rightof 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 QuickSortarr[] --> 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 arrayvoid printArray(char arr[], int size){    for (int i = 0; i < size; i++)        cout << arr[i] << " ";} // Driver codeint 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;}
// Java implementation of the approachclass 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 contributed by ihritik
# Python3 implementation of the above approach """ This function takes last element as pivot,places the pivot element at its correct positionin sorted array, and places all smaller (smaller than pivot) to left of pivot andall 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 QuickSortarr[] --> 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 arraydef printArray(arr, size) :         for i in range(0, size) :        print(arr[i], end = " "); # Driver codeif __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
// C# implementation of the approachusing 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 contributed by ihritik
// JavaScript implementation of the 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 */    function partition( arr, low, high, mod)    {             // pivot        var pivot = arr[high];             // Index of smaller element        var i = (low - 1);             var piv = pivot % mod;        for (var j = low; j <= high - 1; j++)        {                 var 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                var t = arr[i];                arr[i] = arr[j];                arr[j] = t;                 }        }         var 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 */    function quickSort(arr, low, high, mod)    {        if (low < high)        {            /* pi is partitioning index, arr[p] is now            at right place */            var 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    function printArray( arr, size)    {        for (var i = 0; i < size; i++)            document.write(arr[i] + " ");    }         // Driver code        var arr = ['g', 'e', 'e', 'k', 's' ];        var n = arr.length;        var mod = 8;             // Sort the given array        quickSort(arr, 0, n - 1, mod);             // Print the sorted array        printArray(arr, n);         // This code is contributed by shivanisinghss2110
k s e e g
 
Time Complexity: O(n * log n)
Auxiliary Space: O(1)
Method 2: The sorting can also be done using std::sort() and modifying the comparator.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; int M; // Comparator used to sort the array// according to ASCII % Mbool comparator(char ch1, char ch2){    int i = ch1 % M;    int j = ch2 % M;    return (i < j);} // Function to print the given arrayvoid printArray(char arr[], int size){    for (int i = 0; i < size; i++)        cout << arr[i] << " ";} // Driver codeint 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;}
k s e e g
 
Time Complexity: O(n * log n)
Auxiliary Space: O(1)
ankthon
ihritik
subhammahato348
surinderdawra388
ruhelaa48
shivanisinghss2110
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Linear Search
Introduction to Arrays
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm