请教一个入门级二维数组的排序问题
刚刚学习二维数组, 请教大大们一个问题,写好了 但是出错 估计是排序那里有问题 后附代码:题目如下:
1.用户输入行数(1-10)。
2.分配array pointers。如下图
3.每行array的大小为用户输入的数字(1-15)。如下图
4.系统自动将每行array填充随机数字(-99 — 99)。如下图
5.用bubble sort 将每行从大到小排序。如下图
6.用insertion sort 将pointer的长度从长到短,至上而下排序。如下图
7.将结果保存到一个.txt file里面。格式如下:
例1:
4
6: 90 70 60 50 30 10
5: 90 80 60 20 10
3: 35 25 15
2: 99 80
例2:
2
4: 40 30 20 10
3: 30 20 10
我的做法是:
程序代码:
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <crtdbg.h> int** buildTable (void); void bubble (int** table, int size, int num); void insertSort (int** table, int size, int num); void write (FILE* fpDone, int num, int** table, int size); int main( void ) { int **table; int size; int num; FILE* fpDone; table = buildTable (); bubble(table,size,num); printf ("Please wait for system calculate.\n"); write (fpDone, num,table,size); return 0; } int** buildTable(void) { int **table; int size; int num; int r, c; srand(time(NULL)); printf("Enter the number of row: "); scanf("%d", &size); table = (int **) calloc( size + 1, sizeof(int *) ); if( !table ) printf( "Not enough memory!\n" ), exit(101); *(table + size - 1) = NULL; for( r = 0; r < size; r++ ) { printf("Enter number of integers in row %d:", r + 1); scanf("%d",&num); table[r] = (int *) calloc( num+1 , sizeof(int) ); table[r] [0] = num ; if( !table[r] ) printf( "Not enough memory!\n" ), exit(102); table[r][0] = num ; for( c = 1; c <= num + 1; c++ ) table[r][c] = rand() % -99 + 99; } free( table ); printf( _CrtDumpMemoryLeaks() ? "Memory Leak\n" : "No Memory Leak\n"); return table; } void bubble(int** table, int size, int num) { int unsorted=0; int* temp; int i; int r, c; while(unsorted==0) { unsorted=1; for(i=0;i<size-1;i++) { if(table[i] > table[i+1]) { temp = table[i]; table[i] = table[i+1]; table[i+1] = temp; unsorted=0; } } } return; } void insertSort (int** table, int size, int num) { int walk; int* temp; bool located; for (int current =1; current <= size; current++) { located = false; temp = table [current]; for (walk = current - 1; walk >=0 && !located;) if (temp < table[walk]) { table[walk + 1] = table [walk]; walk--; } else located = true; table [walk + 1] = temp; } return; } void write(FILE* fpDone, int num, int** table, int size) { int r,c; if (!(fpDone = fopen("Result.txt", "w"))) { printf("Error! No sorted.txtt file found!\n"); exit(103); } fprintf(fpDone, "The ragged table has %d rows\n\n", size ); fprintf(fpDone,"%2d: ", num ); for( r = 0; table[r] != NULL; r++ ) { num = table[r][0]; fprintf(fpDone,"%2d: ", num ); for( c = 1; c <= num; c++ ) fprintf(fpDone,"%3d ", table[r][c] ); fprintf(fpDone,"\n" ); } fprintf(fpDone, "\n" ); return; }
运行的时候有问题,有大大能帮忙看看吗?