二维数组中的插入排序
Insertion sort in 2d arrays
使用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
您使用了错误的索引。试试这个:
for ( i = 0; i < r; ++i ) {
if ( i % 2 == 0 ) {
for ( j = 0; j < c; ++j ) { // ascending order
min = num[i][j];
for ( k = j + 1; k < c; ++k ) {
if ( num[i][k] < min ) { // just switch the values
min = num[i][k];
num[i][k] = num[i][j];
num[i][j] = min;
}
}
}
} else {
for ( j = 0; j < c; ++j ) { // descending order
max = num[i][j];
for ( k = j + 1; k < c; ++k ) {
if ( num[i][k] > max ) {
max = num[i][k];
num[i][k] = num[i][j];
num[i][j] = max;
}
}
}
}
}
当然,您可以创建两个独立的功能或完全重新考虑您的设计。
相关文章:
- 将二维数组的所有元素插入到一维数组中
- 为什么指针在对二维数组进行排序时无法正常工作?
- 排序后如何将二维数组重置为原始形式
- 对角度二维数组进行排序
- 这是用于对二维数组进行排序的最佳方法
- 按一列对二维数组进行气泡排序
- 根据用户输入对二维数组进行排序和打印
- 在二维数组中插入结构
- 对 C++ 中的二维数组进行排序
- 二维数组中的插入排序
- 在C++中对二维数组使用插入排序函数
- visual C++将整数的二维数组插入到另一个整数的二维阵列中
- 如何在c++中对二维数组进行排序
- 如何在c/c中基于特定索引对二维数组进行排序
- 编写一个程序,使用冒泡排序对二维数组中的整数按升序排序
- 排序二维数组不触及第二次元
- C++中二维数组的冒泡排序
- 用C++对二维数组中的浮点数进行排序
- 大0插入二维数组
- 如何按特定单元格对二维数组进行快速排序?