具有不同col长度的气泡排序矩阵

时间:2014-03-29 08:31:09

标签: c pointers matrix bubble-sort

我需要对具有不同col长度的矩阵进行冒泡排序, 它需要没有[]操作数和语言C. 我试着这样做:

for (i = 0; i < 5; i++)
{
    first = (arr + i+d);// the first value in every line
    for (j = 1; j <= (*first); j++)
    {
        for (d = 0; d <*(first)- j - 1; d++)
        {
            if (*(first+d+i) > *(first+d+1+i) )
            {
                swap =*(first+d);
                *(first+d) = *(first+d+1);
                *(first+d+1) = swap;
            }
        }
    }
}

但它不起作用,有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

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

typedef int Type;

#define PRN_Type "%d"

void print(Type **a, int size){
    for(int i = 0;i<size;++i){
        for(int j=1;j<=a[i][0];++j){
            printf(PRN_Type " ", a[i][j]);
        }
        printf("\n");
    }
}

void b_sort(Type **arr, int size){
    int i, j, d;
    Type swap, *first;
    for (i = 0; i < size; ++i){
        first = arr[i];//!!
        for (j = 1; j <= *first; ++j){
            for (d = 2; d <= *first -j+1; ++d){
                if (*(first+d-1) > *(first+d) ){
                    swap =*(first+d-1);
                    *(first+d-1) = *(first+d);
                    *(first+d) = swap;
                }
            }
        }
    }
}

int main(void){
/*
    int data[5][] = {
        {3, 2,4,1},
        {2, 99, 55},
        {5, 9,5,1,7,5},
        {1, 100},
        {4, 5,5,5,5}
    }
*/
    int size = 5;
    Type **data;
    data = malloc(size * sizeof(Type*));
    data[0]=(Type[]){3, 2,4,1};
    data[1]=(Type[]){2, 99, 55};
    data[2]=(Type[]){5, 9,5,1,7,5};
    data[3]=(Type[]){1, 100};
    data[4]=(Type[]){4, 5,5,5,5};
    print(data, size);
    b_sort(data, size);
    printf("\n");
    print(data, size);
    return 0;
}