Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use 'sort' with char array(C++)

Is it possible to use std::sort defined inside <algorithm> for sorting char arrays according to their ASCII value? If yes, please provide an example.

like image 568
Harish Vishwakarma Avatar asked Jan 01 '13 15:01

Harish Vishwakarma


People also ask

Can I sort a char array?

The main logic is to toCharArray() method of the String class over the input string to create a character array for the input string. Now use Arrays. sort(char c[]) method to sort character array. Use the String class constructor to create a sorted string from a char array.

Can we sort char array in C++?

Yes. That is definitely possible. You could know that just by writing some sample code, such as this: char charArray[] = {'A','Z', 'K', 'L' }; size_t arraySize = sizeof(charArray)/sizeof(*charArray); std::sort(charArray, charArray+arraySize); //print charArray : it will print all chars in ascending order.

Is there a function to sort array in C?

C library function - qsort() The C library function void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*)) sorts an array.


2 Answers

Yes. That is definitely possible. You could know that just by writing some sample code, such as this:

char charArray[] = {'A','Z', 'K', 'L' };

size_t arraySize = sizeof(charArray)/sizeof(*charArray);

std::sort(charArray, charArray+arraySize);

//print charArray : it will print all chars in ascending order.

By the way, you should avoid using c-style arrays, and should prefer using std::array or std::vector.

std::array is used when you know the size at compile-time itself, while std::vector is used when you need dynamic array whose size will be known at runtime.

like image 171
Nawaz Avatar answered Sep 28 '22 07:09

Nawaz


Yes:

char array[] = "zabgqkzg";

std::sort(array, array+sizeof(array));

See http://ideone.com/0TkfDn for a working demo.

like image 42
Oliver Charlesworth Avatar answered Sep 28 '22 08:09

Oliver Charlesworth