Docsity

Sorting an Array and Two Dimensional Arrays in C++, Slides of Computer Programming

Partial preview of the text

Download Sorting an Array and Two Dimensional Arrays in C++ and more Slides Computer Programming in PDF only on Docsity!

Wednesday, April 11, 2012 Computer Programming

Lecture 18

Sorting an array  Lots of applications require sorting  Algorithm for sorting

Sorting an arrayint main(void){int i, j, size=10;double dArray[size]={34, 5.6, 0.9, 345.7, 54.1, 23.5,2.5, 6.78, 12.4, 13.9};double temp;for (i=0; i<size; i++){for (j=i+1; j<size; j++){

if (dArray[j]<dArray[i]){temp=dArray[j];dArray[j]=dArray[i];dArray[i]=temp;} } }^ //in-place sortingreturn 0; }

Self Test: Sorting an array Modify the previous program so that it does notdo in-place sorting, but instead stores the sortedlist in another array.

Self Test: Sorting an array (Simulate) // This is the bubble sort.for(a=1; a<size; a++)for(b=size-1; b>=a; b--) {if(nums[b-1] > nums[b]) { // if out of order// exchange elementst = nums[b-1];nums[b-1] = nums[b];nums[b] = t;} } // This is the end of the bubble sort.

Bubble Sort Simulation

Two dimensional arrays int^ array[2][3]

=^ {{1,2,3},{4,5,6}};

int^ E[][2]={

Accessing Array Elements ^ int matrix[3][4];^ ^ matrix has 12 integer elements^ ^ matrix[0][0]

element in first row, first column ^ matrix[2][3]

element in last row, last column

int main(){^ const int rows=3,

cols=4; int i,^

j,^ num[rows][cols]; for(i=0;

i<rows;

++i)^ { for(j=0;

j<cols;

++j)^ { num[i][j]=

(i*cols)+j+1; cout <<

num[i][j]<<"\t"; } cout <<

"\n"; } return 0;} // output?

Two Dimensional Arrays

Output: 1 2

Output: 1 2

Self Test: Arrays Print the transpose of a 2-D array.

Practice Exercise! ^ Write down the code to multiply twomatrices of sizes NxM and MxQrespectively.

Arrays int a[10] = {1,2,3,4,0,3,4,6,7,8};int x=3; y=1;cout<< a[x+2*y] <<“\n”;cout<<“Answer= “<<a[a[a[4]]]<<“\n”;Output?