How to change the order of the subcategory and category in a post?

You can write a get_the_terms filter to change the other the category values are returned, e.g.

function sort_the_terms( $terms, $post_id, $taxonomy ) {
    if ( 'categories' === $taxonomy ) {
        usort( $terms, function( $term1, $term2 ) {
            // Better sort logic here
            return $term1->name <=> $term2->name;
        } );
    }
    return $terms;
}
add_filter( 'get_the_terms', 'sort_the_terms', 20, 3 );

You’ll need to change the logic in the comparator to get the order you want, e.g. using information in wp_termmeta or the group or parent ID of the term. (If you’re using parents to build a hierarchy you might need something more complicated than just a usort though, since ‘place in hierarchy’ is going to be difficult to determine completely in a comparator.)