2012-12-30 24 views
5

我想排序2維array.the原始數組2維數組是排序在C

5 0 3 
4 1 2 
3 1 1 
4 2 2 
3 3 1 

當排序,應該是這樣

3 1 1 
3 3 1 
4 2 2 
4 1 2 
5 0 3 

這裏是我的代碼用於嘗試實現Bubble Sort,我表示行數。

int x,y,z,j,temp1,temp2,temp3; 
for(x=0;x<i;x++) 
{ 
    for (j=0;j<i-1;j++) 
    { 
     if(a[j][0]>a[j+1][0]) 
     { 
      temp1=a[j][0]; 
      temp2=a[j][1]; 
      temp3=a[j][2]; 
      a[j][0]=a[j+1][0]; 
      a[j][1]=a[j+1][1]; 
      a[j][2]=a[j+1][2]; 
      a[j+1][0]=temp1; 
      a[j+1][1]=temp2; 
      a[j+1][2]=temp3; 
     } 
    } 
} 

它仍然沒有排序,任何幫助將不勝感激。

+13

你的支架樣式是好奇。 – moonwave99

+8

爲什麼'4 2 2'出現在'4 1 2'之前? – pmg

+1

好的提示是你不要在循環之外使用變量'x'。 – Hogan

回答

3

看起來您正在嘗試對lexicographical order中的數組行進行排序。如果將二維數組視爲數組數組,則只需將第一級數組中的第二級數組按照升序排列順序排序即可。

根據陣列中的列數是否固定,您可以使用qsort函數和自定義比較器來完成此操作。例如,如果你知道總會有在每列正好3個元素,你可以寫一個比較像這樣的:

static const size_t NUM_COLS = 3; 

/* Lexicographically compare two arrays of size NUM_COLS. */ 
int CompareArrays(const void* arr1, const void* arr2) { 
    /* Convert back to the proper type. */ 
    const int* one = (const int*) arr1; 
    const int* two = (const int*) arr2; 

    /* Do an element-by-element comparison. If a mismatch is found, report how 
     * the arrays compare against one another. 
     */ 
    for (size_t i = 0; i < NUM_COLS; i++) { 
     if (one[i] < two[i]) return -1; 
     if (one[i] > two[i]) return +1; 
    } 

    /* If we get here, the arrays are equal to one another. */ 
    return 0; 
} 

/* Use qsort to sort the arrays */ 
qsort((const int*)&one, numRows, sizeof(int[NUM_COLS]), CompareArrays); 

希望這有助於!在C

-1

排序2D陣列

int x[5][5],i,j,i1,j1,temp,k; 

for (int i=0;i<5;i++) 
for (int j=0:<5;j++) 
cin>>x[i][j]; 


for (int i=0;i<5;i++) 
    for (int j=0:<5;j++) 
{ 
    k=j+1; 
      for (int i1=0;i<5;i1++) 
      { 
       for (int j1=k:<5;j1++) 
        { 
        if (x[i,j]>x[i1,j1]) 
         { 
         temp=x[i,j]; 
         x[i,j]=x[i1,j1]; 
         x[i1,j1]=temp; 
         } 
        } 
       k=1; 
      } 
} 


for (int i=0;i<5;i++) 
for (int j=0:<5;j++) 
cout<<x[i][j];