PropellerAds
Posted by : Unknown Monday 22 December 2014

This program demonstrate how to sort 2d array in ascending order. The program explain it in 3x3 array you could change the values as required to meet your requirement

//prog for 2d array sort

#include<iostream>
#include<conio.h>

using namespace std;

void main() {
int arr[3][3];
int temp;

cout << "Enter 9 elements\n\n";

//Enter Element
for(int j = 0; j < 3; j++){
for(int i = 0; i < 3; i++){
cout << "Enter Elements no: " << i+j+1 << " : ";
cin >> arr[i][j];
}
}
cout <<  endl;

//print array
for(int j = 0; j < 3; j++){
for(int i = 0; i < 3; i++){
cout << arr[i][j] << "\t" ;
}
cout <<  endl;
}

// run the loop double times the number of row or column which ever is greater
for (int k = 0; k <6; k++){
//arrage elemnt in ascending order in a rows
for (int i = 0; i < 2; i++){
for (int j = 0; j < 3; j++){
if(arr[i][j] > arr[i+1][j]){
temp = arr[i][j];
arr[i][j] = arr[i+1][j];
arr[i+1][j] = temp;
}
}

//compare the last element of each row with first element of its next row
for (int i = 0; i < 2; i++){
if(arr[2][i] > arr[0][i+1]){
temp = arr[2][i];
arr[2][i]  = arr[0][i+1];
arr[0][i+1] = temp;
}
}
}



}
cout <<  endl << endl;

// print array
for(int j = 0; j < 3; j++){
for(int i = 0; i < 3; i++){
cout << arr[i][j] << "\t" ;
}
cout <<  endl;
}
_getch();
}



This program arrange the rows value in in itself and then compare the last value of a row with the first value of the next row. And if it is greater it swaps them and again  arrange the the row. The program continue to do it unless all the value get sorted. Go through the program and you will get it how it works

{ 1 comments... read them below or add one }

  1. there's some errors in the code like multiple variable declaration but still its good! :D

    ReplyDelete

PropellerAds
PropellerAds

Popular Post

Powered by Blogger.

- Copyright © BSCS -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -