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