Sunday, August 2, 2009

How to sort an array of characters (alphabatically) in c++??

use ascii value to perform the sort


the logic is 'a' has lowest ascii value than others

How to sort an array of characters (alphabatically) in c++??
If all the characters are the same case, then I don't believe you have to use the ascii values. You can do a comparison a %26lt; b and it will evaluate to true or false. Then do a bubble sort or whichever sort you prefer.





Here's an example I just did.





#include %26lt;iostream%26gt;


#include %26lt;cstdlib%26gt;


using namespace std;





int main()


{


char chars[] = {'a','d','b','g','e','c','f'};


int size = 7;


char temp;





for(int i = 0; i %26lt; size; i++)


for(int j = 0; j %26lt; size-1; j++)


{


if(chars[j+1] %26lt; chars[j])


{


temp = chars[j];


chars[j] = chars[j+1];


chars[j+1] = temp;


}


}





for(int i = 0; i %26lt; size; i++)


cout%26lt;%26lt;chars[i] %26lt;%26lt;" ";





return 0;


}
Reply:Read the value from an array and find its ASCII (which is easy try to read a character as integer and it will return an integer vakue which is the character's ASCII value) value and sort it using any Sorting algorithms like Bubble sort, quick sort , Radix Sort , ETC. Once the array is sorted according to the ASCII value - You now just need to read the array as a character array coz the whole array has been automatically alphabetically sorted .


No comments:

Post a Comment