Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides: www.nanamic.org.uk/T%20.../bubblesortexample.ppt.

Similar presentations


Presentation on theme: "CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides: www.nanamic.org.uk/T%20.../bubblesortexample.ppt."— Presentation transcript:

1 CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides: www.nanamic.org.uk/T%20.../bubblesortexample.ppt http://freedownload.is/ppt/c-programming-skills-part-4-arrays-119712.html 2003 Prentice Hall, Inc.

2 Applications of Arrays

3 Searching Arrays: Linear Search Search array for a key value Linear search Compare each element of array with key value Start at one end, go to other Useful for small and unsorted arrays Inefficient, if search key not present, examines every element

4  2003 Prentice Hall, Inc. All rights reserved. Outline // The function compares key to every element of array until location // is found or until end of array is reached; return subscript of // element key or -1 if key not found int linearSearch( const int array[], int key, int sizeOfArray ) { for ( int j = 0; j < sizeOfArray; j++ ) if ( array[ j ] == key ) // if found, return j; // return location of key return -1; // key not found } // end function linearSearch Linear Search Function

5 Sorting Arrays : Bubble sort revisit Sorting data: (arranging data elements in ascending or descending order: Important computing application Every organization sometimes requires to sort some data Bubble sort Several passes through the array Successive pairs of elements are compared If increasing order (or identical), no change If decreasing order, elements exchanged Repeat these steps for every element

6 Bubble Sort Example 9, 6, 2, 12, 11, 9, 3, 7 6, 9, 2, 12, 11, 9, 3, 7 6, 2, 9, 12, 11, 9, 3, 7 6, 2, 9, 11, 12, 9, 3, 7 6, 2, 9, 11, 9, 12, 3, 7 6, 2, 9, 11, 9, 3, 12, 7 6, 2, 9, 11, 9, 3, 7, 12 The 12 is greater than the 7 so they are exchanged. The 12 is greater than the 3 so they are exchanged. The twelve is greater than the 9 so they are exchanged The 12 is larger than the 11 so they are exchanged. In the third comparison, the 9 is not larger than the 12 so no exchange is made. We move on to compare the next pair without any change to the list. Now the next pair of numbers are compared. Again the 9 is the larger and so this pair is also exchanged. Bubblesort compares the numbers in pairs from left to right exchanging when necessary. Here the first number is compared to the second and as it is larger they are exchanged. The end of the list has been reached so this is the end of the first pass. The twelve at the end of the list must be largest number in the list and so is now in the correct position. We now start a new pass from left to right.

7 Bubble Sort Example 6, 2, 9, 11, 9, 3, 7, 122, 6, 9, 11, 9, 3, 7, 122, 6, 9, 9, 11, 3, 7, 122, 6, 9, 9, 3, 11, 7, 122, 6, 9, 9, 3, 7, 11, 12 6, 2, 9, 11, 9, 3, 7, 12 Notice that this time we do not have to compare the last two numbers as we know the 12 is in position. This pass therefore only requires 6 comparisons. First Pass Second Pass

8 Bubble Sort Example 2, 6, 9, 9, 3, 7, 11, 122, 6, 9, 3, 9, 7, 11, 122, 6, 9, 3, 7, 9, 11, 12 6, 2, 9, 11, 9, 3, 7, 12 2, 6, 9, 9, 3, 7, 11, 12 Second Pass First Pass Third Pass This time the 11 and 12 are in position. This pass therefore only requires 5 comparisons.

9 Bubble Sort Example 2, 6, 9, 3, 7, 9, 11, 122, 6, 3, 9, 7, 9, 11, 122, 6, 3, 7, 9, 9, 11, 12 6, 2, 9, 11, 9, 3, 7, 12 2, 6, 9, 9, 3, 7, 11, 12 Second Pass First Pass Third Pass Each pass requires fewer comparisons. This time only 4 are needed. 2, 6, 9, 3, 7, 9, 11, 12 Fourth Pass

10 Bubble Sort Example 2, 6, 3, 7, 9, 9, 11, 122, 3, 6, 7, 9, 9, 11, 12 6, 2, 9, 11, 9, 3, 7, 12 2, 6, 9, 9, 3, 7, 11, 12 Second Pass First Pass Third Pass The list is now sorted but the algorithm does not know this until it completes a pass with no exchanges. 2, 6, 9, 3, 7, 9, 11, 12 Fourth Pass 2, 6, 3, 7, 9, 9, 11, 12 Fifth Pass

11 Bubble Sort Example 2, 3, 6, 7, 9, 9, 11, 12 6, 2, 9, 11, 9, 3, 7, 12 2, 6, 9, 9, 3, 7, 11, 12 Second Pass First Pass Third Pass 2, 6, 9, 3, 7, 9, 11, 12 Fourth Pass 2, 6, 3, 7, 9, 9, 11, 12 Fifth Pass Sixth Pass 2, 3, 6, 7, 9, 9, 11, 12 This pass no exchanges are made so the algorithm knows the list is sorted. It can therefore save time by not doing the final pass. With other lists this check could save much more work.

12 Bubble Sort Example Quiz 1.Which number is definitely in its correct position at the end of the first pass? Answer: The last number must be the largest. Answer: Each pass requires one fewer comparison than the last. Answer: When a pass with no exchanges occurs. 2.How does the number of comparisons required change as the pass number increases? 3.How does the algorithm know when the list is sorted? 4.What is the maximum number of comparisons required for a list of 10 numbers? Answer: 9 comparisons, then 8, 7, 6, 5, 4, 3, 2, 1 so total 45

13 // This function sorts an array with bubble sort algorithm void bubbleSort( int a[], int size ) { int temp; // temporary variable used to swap elements // loop to control number of passes for ( int pass = 1; pass < size; pass++ ) // loop to control number of comparisons per pass for ( int j = 0; j < size – 1 ; j++ ) // swap elements if out of order if ( a[ j ] > a[ j + 1 ] ) { temp = a[ j ]; a[ j ] = a[ j + 1 ]; a[ j + 1 ] = temp; } // end if } // end function bubbleSort Bubble Sort Function code To reduce the number of comparisons, the for-loop continuation-condition can be written as: j < size – pass e.g., if size=5: Pass 1  4 comparisons Pass 2  3 comparisons Pass 3  2 comparisons Pass 4  1 comparison

14 Binary search Only used with sorted arrays Compare middle element with key If equal, match found If key < middle Repeat search on first half of array If key > middle Repeat search on last half Very fast At most N steps, where 2 > Number of elements 30 element array takes at most 5 steps (2 5 > 30 )

15 Binary Search This algorithm is for finding an item in a sorted list or determining that it is not in the list. Is Mr Naeem in the list opposite? This algorithm is for finding an item in a sorted list or determining that it is not in the list. Is Mr Naeem in the list opposite? Mr Naeem? 1. Mr Ghafoor 2. Mr Ghazanfar 3. Mr Hamid 4. Mr Naeem 5. Mr Rashid 6. Mr Sarfraz 7. Mr Sohail 8. Mr Tahir 9. Mr Osman 10. Mr Zafar First find the middle of the list: (10+1)/2 = 5.5 so take 6 th item First find the middle of the list: (10+1)/2 = 5.5 so take 6 th item ? Compare Mr Naeem and Mr Sarfraz, Naeem comes before Sarfraz so reduce the list to the first half. Compare Mr Naeem and Mr Sarfraz, Naeem comes before Sarfraz so reduce the list to the first half.

16 Binary Search Mr Naeem ? Now find the middle (1+5)/2 = 3 rd item Now find the middle (1+5)/2 = 3 rd item Compare Mr Naeem and Mr Hmid, Naeem comes after Hamid so reduce the list to the second half. Compare Mr Naeem and Mr Hmid, Naeem comes after Hamid so reduce the list to the second half. 1. Mr Ghafoor 2. Mr Ghazanfar 3. Mr Hamid 4. Mr Naeem 5. Mr Rashid ? 1. Mr Ghafoor 2. Mr Ghazanfar 3. Mr Hamid 4. Mr Naeem 5. Mr Rashid 6. Mr Sarfraz 7. Mr Sohail 8. Mr Tahir 9. Mr Osman 10. Mr Zafar

17 Binary Search Mr Naeem? Find the middle (4+5)/2 = 4.5 so take item 5 Find the middle (4+5)/2 = 4.5 so take item 5 Compare Mr Naeem and Mr Rashid, Naeem comes before Rashid so take first half of list 4. Mr Naeem 5. Mr Rashid ? 1. Mr Ghafoor 2. Mr Ghazanfar 3. Mr Hamid 4. Mr Naeem 5. Mr Rashid 6. Mr Sarfraz 7. Mr Sohail 8. Mr Tahir 9. Mr Osman 10. Mr Zafar 1. Mr Ghafoor 2. Mr Ghazanfar 3. Mr Hamid 4. Mr Naeem 5. Mr Rashid

18 Binary Search Mr Naeem? Compare Mr Naeem and Mr Naeem, We have found him! Compare Mr Naeem and Mr Naeem, We have found him! 4. Mr Naeem ? 1. Mr Ghafoor 2. Mr Ghazanfar 3. Mr Hamid 4. Mr Naeem 5. Mr Rashid 6. Mr Sarfraz 7. Mr Sohail 8. Mr Tahir 9. Mr Osman 10. Mr Zafar 1. Mr Ghafoor 2. Mr Ghazanfar 3. Mr Hamid 4. Mr Naeem 5. Mr Rashid 4. Mr Naeem 5. Mr Rashid

19 Multiple-Subscripted Arrays Multiple subscripts a[ i ][ j ] Tables with rows and columns Specify row, then column “Array of arrays” a[0] is an array of 4 elements a[0][0] is the first element of that array Row 0 Row 1 Row 2 Column 0Column 1Column 2Column 3 a[ 0 ][ 0 ] a[ 1 ][ 0 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 3 ] a[ 2 ][ 3 ] Row subscript Array name Column subscript

20 Two-dimensional Array: Referencing Referenced like normal cout << b[ 0 ][ 1 ]; Outputs 0 Cannot reference using commas, Syntax error cout << b[ 0, 1 ]; Function prototypes Must specify sizes of subscripts First subscript not necessary, as with single-scripted arrays void printArray( int [][ 3 ] ); 1 0 3 4

21 // Initializing and printing multidimensional arrays. #include void printArray( int [][ 3 ] ); int main() { int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } }; int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 }; int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } }; cout << "Values in array1 by row are:" << endl; printArray( array1 ); cout << "Values in array2 by row are:" << endl; printArray( array2 ); cout << "Values in array3 by row are:" << endl; printArray( array3 ); return 0; // indicates successful termination } // end main Note the various initialization styles. The elements in array2 are assigned to the first row and then the second. Note the format of the prototype.

22 // Function to output array with two rows and three columns void printArray( int a[][ 3 ] ) { for ( int r = 0; r < 2; r++ ) { // for each row for ( int c = 0; c < 3; c++ ) // output column values cout << a[ r ][ c ] << ' '; cout << endl; // start new line of output } // end outer for structure } // end function printArray Values in array1 by row are: 1 2 3 4 5 6 Values in array2 by row are: 1 2 3 4 5 0 Values in array3 by row are: 1 2 0 4 0 0 For-loops are often used to iterate through arrays. Nested loops are helpful with multiple-subscripted arrays.

23 Multidimensional Arrays and Parallel Arrays Example: Tracking Students Grades Use initialized data Keep track of students grades Uses two-dimensional array (table) Rows are students Columns are grades Use functions: To find out minimum & maximum grades To Calculate average grades To print the result 95 85 89 80 Exam1 Exam2 Student0 Student1

24 // Tracking Students grades example. #include const int students = 3; // number of students const int exams = 4; // number of exams // function prototypes int minimum( int [][ exams ], int, int ); int maximum( int [][ exams ], int, int ); double average( int [], int ); void printArray( int [][ exams ], int, int ); int main() { // initialize student grades for three students (rows) int studentGrades[ students ][ exams ] = { { 77, 68, 86, 73 }, { 96, 87, 89, 78 }, { 70, 90, 86, 81 } }; // output array studentGrades cout << "The array is:\n"; printArray( studentGrades, students, exams ); // determine smallest and largest grade values cout << "\n\nLowest grade: " << minimum( studentGrades, students, exams ) << "\nHighest grade: " << maximum( studentGrades, students, exams ) << '\n';

25 // calculate average grade for each student for ( int person = 0; person < students; person++ ) cout << "The average grade for student " << person << " is " << average( studentGrades[ person ], exams ) << endl; return 0; // indicates successful termination } // end main // The following function finds minimum grade int minimum( int grades[][ exams ], int pupils, int tests ) { int lowGrade = 100; // initialize to highest possible grade for ( int i = 0; i < pupils; i++ ) for ( int j = 0; j < tests; j++ ) if ( grades[ i ][ j ] < lowGrade ) lowGrade = grades[ i ][ j ]; return lowGrade; } // end function minimum Determines the average for one student. We pass the array/row containing the student’s grades. Note that studentGrades[0] is itself an array.

26 // The following function finds maximum grade of all grades int maximum( int grades[][ exams ], int pupils, int tests ) { int highGrade = 0; // initialize to lowest possible grade for ( int i = 0; i < pupils; i++ ) for ( int j = 0; j < tests; j++ ) if ( grades[ i ][ j ] > highGrade ) highGrade = grades[ i ][ j ]; return highGrade; } // end function maximum

27 // The following function determines average grade for particular student double average( int setOfGrades[], int tests ) { int sum = 0; // total all grades for one student for ( int i = 0; i < tests; i++ ) sum += setOfGrades[ i ]; return static_cast ( sum ) / tests; // average } // end function maximum

28 // The following function prints the two-dimensional array of students grades void printArray( int grades[][ exams ], int pupils, int tests ) { // set left justification and output column heads cout << left << " [0] [1] [2] [3]"; // output grades in tabular format for ( int i = 0; i < pupils; i++ ) { // output label for row cout << "\nstudentGrades[" << i << "] "; // output one grades for one student for ( int j = 0; j < tests; j++ ) cout << setw( 5 ) << grades[ i ][ j ]; } // end outer for } // end function printArray

29 The array is: [0] [1] [2] [3] studentGrades[0] 77 68 86 73 studentGrades[1] 96 87 89 78 studentGrades[2] 70 90 86 81 Lowest grade: 68 Highest grade: 96 The average grade for student 0 is 76.00 The average grade for student 1 is 87.50 The average grade for student 2 is 81.75


Download ppt "CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides: www.nanamic.org.uk/T%20.../bubblesortexample.ppt."

Similar presentations


Ads by Google