0
使用Borland Turbo C++,我製作了該程序來演示2D數組中的插入排序。輸出是錯誤的,似乎有一個邏輯錯誤,我無法找到。這裏的插入排序算法是按升序排列所有偶數行,而所有奇數行按降序排序。 sort()函數應該分解成evensort()和oddsort()嗎?在二維數組中插入排序
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
int num[5][3];
int i, j,r,c;
void input(int r, int c)
{ cout<<"Enter the elements into the array"<<endl;
for(i=0; i<r; i++)
for(j=0; j<c;j++)
cin>>num[i][j];
}
void sort(int r, int c)
{ for(i=0; i<r; i++)
{ for(j=0; j<c; j++)
if(i%2==0)
{ int min=num[i][j],pos=i;
for(int k=i+1; k<r; k++)
{ if(num[k][j]<min)
num[k][j]=min;
pos=k;
}
num[pos][j]=num[i][j];
num[i][j]=min;
}
else
{ int max=num[i][j],pos1=i;
for(int l=i+1; l<r; l++)
{ if(num[l][j]>max)
num[l][j]=max;
pos1=l;
}
num[pos1][j]=num[i][j];
num[i][j]=max;
}
}
}
void display(int r, int c)
{ cout<<endl<<"Array is"<<endl;
for(i=0; i<r; i++)
{ cout<<"\n";
for(j=0; j<c;j++)
{
cout<<num[i][j]<<"\t";
}
}
}
void main()
{ clrscr();
cout<<"Enter the no of rows"<<endl;
cin>>r;
cout<<"Enter the no of columns"<<endl;
cin>>c;
if(r<=5 && c<=3)
{ input(r,c);
cout<<" Before sorting"<<endl;
display(r,c);
sort(r,c);
cout<<"\n After sorting"<<endl;
display(r,c);
}
else cout<<"Invalid no of rows and columns";
getch();
}
輸出:
Enter the number of rows
4
Enter the number of columns
3
Enter the elements into the array
1 2 3 4 5 6 7 8 9 10 11 12
Array before sorting is
1 2 3
4 5 6
7 8 9
10 11 12
Array after sorting is
1 2 3
4 5 6
4 5 6
4 5 6