Open In App

Sort the character array based on ASCII % N

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// 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;
}


Java




// 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 contributed by ihritik


Python3




# 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


C#




// 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 contributed by ihritik


Javascript




// 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


Output

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 % 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;
}


Java




/*package whatever //do not write package name here */
import java.util.*;
 
class GFG {
 
  static int M;
 
  // Function to print the given array
  static void printArray(ArrayList<Character> arr, int size)
  {
    for (int i = 0; i < size; i++)
      System.out.print(arr.get(i) + " ");
  }
 
  public static void main (String[] args) {
    ArrayList<Character> arr = new ArrayList<Character>();
    arr.add('g');
    arr.add('e');
    arr.add('e');
    arr.add('k');
    arr.add('s');
    int n = arr.size();
    M = 8;
 
    // Sort the given array
    Collections.sort(arr,(ch1,ch2)->{
      int i = (int)ch1 % M;
      int j = (int)ch2 % M;
      return i-j;
    });
 
    // Print the sorted array
    printArray(arr, n);
 
  }
}
 
// This code is contributed by aadityaburujwale.


Python3




# Python
def printArray(arr, size):
  for i in range(size):
    print(arr[i] + " ", end="")
 
def main():
  arr = ["g", "e", "e", "k", "s"]
  n = len(arr)
  M = 8
 
  # Sort the given array
  arr.sort(key=lambda ch: ord(ch) % M)
 
  # Print the sorted array
  printArray(arr, n)
 
main()
 
# This code is contributed by akashish__


C#




/*package whatever //do not write package name here */
using System;
using System.Collections.Generic;
using System.Linq;
 
public class GFG{
 
  static int M;
 
  // Function to print the given array
  static void printArray(List<char> arr, int size)
  {
    for (int i = 0; i < size; i++)
      Console.Write(arr[i] + " ");
  }
 
  static public void Main (){
    List<char> arr = new List<char>();
    arr.Add('g');
    arr.Add('e');
    arr.Add('e');
    arr.Add('k');
    arr.Add('s');
    int n = arr.Count();
    M = 8;
 
    // Sort the given array
    arr = arr.OrderBy(c => c % M).ToList();
 
    // Print the sorted array
    printArray(arr, n);
 
  }
}
 
// This code is contributed by akashish__


Javascript




// JavaScript to find CamelCase Pattern
// matching
 
function printArray(arr, size) {
  for (let i = 0; i < size; i++) {
    console.log(arr[i] + " ");
  }
}
 
function main() {
  let arr = ["g", "e", "e", "k", "s"];
  const n = arr.length;
  const M = 8;
 
  // Sort the given array
  arr.sort((ch1, ch2) => {
    let i = ch1.charCodeAt(0) % M;
    let j = ch2.charCodeAt(0) % M;
    return i - j;
  });
 
  // Print the sorted array
  printArray(arr, n);
}
 
main();


Output

k s e e g

Time Complexity: O(n * log n)
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads