繁体   English   中英

C 中的冒泡排序二维数组

[英]Bubble sort 2D array in C

我需要一个 function 对这个随机生成的二维数组进行冒泡排序。 同样使用 rand() 方法,我希望它生成 (1, 1000000) 之间的数字,但它没有给出所需的范围,有什么建议可以找到解决方案吗?

int **matrix()
{

    int **matrix;
    int row, column;
    long s, k;
    int i,j,f,swap;


    srand(time(NULL));
    printf("Number of rows: ");
    scanf("%d", &row);

    printf("Number of column: ");
    scanf("%d", &column);


    matrix = (int **) calloc(row, sizeof(int));


    for(i = 0; i < row; i++)
        matrix[i] = (int *) calloc(column, sizeof(int));


    for(s = 0; s < row; s++)
    {
        for(k = 0; k < column; k++)
        {

            matrix[s][k]=rand()%10000000;
        }
    }

    for(s = 0; s < row; s++)
    {
        for(k = 0; k < column; k++)
            printf("%4d \t\t", matrix[s][k]);

        printf("\n");
    }


    for(i = 0; i < row; i++)
        free((void *) matrix[i]);


    free((void *) matrix);

    return **matrix;

}

使用冒泡排序对二维数组进行排序与对一维数组进行排序略有不同。 这个例子可能有助于你的问题的那一部分。

其他问题

基于此部分:

for(i = 0; i < row; i++)
     matrix[i] = (int *) calloc(column, sizeof(int));

上一节中的行:

 matrix = (int **) calloc(row, sizeof(int));
                                        ^

应该为int *

 matrix = calloc(row, sizeof(int *));
                                 ^

(注意calloc()的强制转换也被删除了。在 C 中,不推荐使用 [c][m][re]alloc 的返回。)

同样使用 rand()方法,我希望它生成 (1, 1000000) 之间的数字,但它没有给出所需的范围,有什么建议可以找到解决方案吗?

(感谢这个答案

rand()扩展以提供 1000000 个唯一值的随机分布:

unsigned long rand_ex(void);

int main(void){

    srand(clock());
    for(int  i=0;i<100;i++)
    {
        printf("%10d:  %10lu\n", i, rand_ex());
    }
    return 0;
}

unsigned long rand_ex(void)
{     
    unsigned long x;
    x = rand();
    x <<= 15;
    x ^= rand();
    x %= 1000001;

    return x;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM