使用 qsort 对二维数组进行排序 [英] Sorting a 2D array with qsort

查看:39
本文介绍了使用 qsort 对二维数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对二维数组进行排序.首先我按列排序,然后按行排序.逐列有效,但逐行无效.这段代码有什么问题?

I'm trying to sort 2d array. First i sort it by column, then by rows. Column by column is working but row by row not. What's wrong in this code?

int scmpr (const void *a, const void *b){ 
return strcmp((const char*)a, (const char*)b);
}

int main(void){
  int i,j;

  char **tab;
  tab=(char**)malloc(sizeof(char*)* 10); 

  for(i=0; i<10; i++){
    tab[i]=(char*)malloc(sizeof(char)*15);
  }

  for(i=0; i<10; i++){
    for(j=0; j<15; j++){
      tab[i][j]=rand()%20+'b';
      printf("%c ", tab[i][j]);
    }
    puts("");
  }
  for (i = 0; i<10; i++){
    qsort(&tab[i][0], 15, sizeof(char), scmpr); 
  }
  qsort(tab, 10, sizeof(char), scmpr); //<-- doesn't work

    for(i=0; i<10; i++){
      for(j=0; j<15; j++){
        printf("%c ", tab[i][j]);
      }
    puts("");
    } 
  puts("");
  return 0;
  }

推荐答案

我认为你的意思是以下

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define M   10
#define N   15

int ccmp( const void *lhs, const void *rhs )
{
    unsigned char c1 = *( const unsigned char *)lhs;
    unsigned char c2 = *( const unsigned char *)rhs; 

    if ( c1 < c2 ) return -1;
    else if ( c2 < c1 ) return 1;
    else return 0;
}

int scmp( const void *lhs, const void *rhs )
{
    return strcmp( *( const char ** )lhs, *( const char ** )rhs );
}

int main( void ) 
{
    char **tab;
    tab = ( char** )malloc( M * sizeof( char* ) ); 

    for ( size_t i = 0; i < M; i++ )
    {
        tab[i] = ( char* )malloc( N * sizeof( char ) );
    }

    srand( ( unsigned int )time( NULL ) );

    for ( size_t i = 0; i < M; i++ )
    {
        for ( size_t j = 0; j < N - 1; j++ )
        {
            tab[i][j] = rand() % ( 'Z' - 'A' + 1 ) + 'A';
        }
        tab[i][N-1] = '';
    }

    for ( size_t i = 0; i < M; i++ )
    {
        printf( "%s
", tab[i] );
    }

    printf( "
" );

    for ( size_t i = 0; i < M; i++ )
    {
        qsort( tab[i], N - 1, sizeof( char ), ccmp ); 
    }
    qsort( tab, M, sizeof( char * ), scmp );

    for ( size_t i = 0; i < M; i++ )
    {
        printf( "%s
", tab[i] );
    }

    printf( "
" );

    for ( size_t i = 0; i < M; i++ ) free( tab[i] );
    free( tab );

    return 0;
}

程序输出可能如下所示

DJSKLJOHGHEANW
ZSDZJZXCKGYOVF
LHEOQYAEHOLPYR
PLORDTQOSNQFVP
TQUEYAVQYVUHKH
WIZOVPHYKXPEMF
JHUFARLARGQSEN
BOWYYXOTMVTYUI
DIOOPKVPDHPXPI
PTXQJVQHTGCHDY

AAEFGHJLNQRRSU
ADEGHHJJKLNOSW
AEEHHLLOOPQRYY
AEHHKQQTUUVVYY
BIMOOTTUVWXYYY
CDFGJKOSVXYZZZ
CDGHHJPQQTTVXY
DDHIIKOOPPPPVX
DFLNOOPPQQRSTV
EFHIKMOPPVWXYZ

这篇关于使用 qsort 对二维数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆