Sorting 2D array of C ++ characters
I have a 2d character array where in each line I store the name ... for example:
J O H N
P E T E R
S T E P H E N
A R N O L D
J A C K
How do I need to sort the array so that I end up with
A R N O L D
J A C K
J O H N
P E T E R
S T E P H E N
This is a 2nd character array ..... no strings or char points .....
a source to share
#define MAX_NAME 8
char names[][MAX_NAME] = {"JOHN", "PETER", "STEPHEN", "ARNOLD", "JACK"};
// strcmp is really (int (*)(const char *, const char *)), so we cast.
qsort(names, sizeof(names) / MAX_NAME, MAX_NAME,
(int (*)(const void *, const void *)) strcmp);
Note that this is probably not a bubble sort.
a source to share
Don't bubble sort - point number 1.
Point number two:
Compare the first character of each auxiliary array (that is, the [x] [0] array) if you need to shift it, and then shift all characters in the sub-array x using a while ... loop or by keeping the sub-array and moving it like this ...
a source to share
C ++ does not support C-style array copying or comparison, but does support such operations on very thin C-style arrays. Try boost::array
which is the same as tr1::array
and std::array
in C ++ 0x.
Or roll your own:
#include <algorithm>
template< class T, size_t s >
struct array {
T arr[s]; // public data, no destructor, inheritance, virtuals, etc
// => type is aggregate
operator T const *() const { return arr; }
operator T *() { return arr; } // as close as we can get to array emulation
friend bool operator< ( array const &l, array const &r )
{ return std::lexicographical_compare( l, l+s, r, r+s ); }
};
array< char, 10 > names[] // aggregate initialization — this is standard C++
= { "JOHN", "PETER", "ARNOLD", "JACK" };
#include <iostream>
using namespace std;
int main() {
sort( names, names + sizeof names / sizeof *names );
for ( array<char,10> *s = names; s != names + sizeof names/sizeof*names; ++ s )
cerr << *s << endl;
}
If your compiler isn't crazy about adding padding to the above structure, you can safely reinterpret_cast
create a C-style array a array
:
template< class T, size_t s >
array< T, s > &wrap_arr( T (&a)[s] ) {
return reinterpret_cast< array<T,s> & >( a );
// make sure the compiler isn't really wacky...
// I would call this optional:
BOOST_STATIC_ASSERT( sizeof( T[s] ) == sizeof( array<T,s> ) );
}
char names_c[][10] // or whatever C input from wherever
= { "JOHN", "PETER", "ARNOLD", "JACK" };
array<char, 10> *names = &wrap_arr( names_c[0] );
a source to share