CS 108 Notes for March 1, 2016. #include //My file 1.c int main (void) { char c = 'z' ; char c_array [10] ; int i = 666 ; int i_array [10] ; float f =

Slides:



Advertisements
Similar presentations
Lesson 8 Searching and Sorting Arrays 1CS 1 Lesson 8 -- John Cole.
Advertisements

The simple built-in data types of the C language such as int, float, - are not sufficient to represent complex data such as lists, tables, vectors, and.
Bubble Sort Algorithm 1.Initialize the size of the list to be sorted to be the actual size of the list. 2.Loop through the list until no element needs.
Programming and Data Structure
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 9A Sorting (Concepts)
 Sort: arrange values into an order  Alphabetical  Ascending numeric  Descending numeric  Does come before or after “%”?  Two algorithms considered.
CS 106 Introduction to Computer Science I 02 / 29 / 2008 Instructor: Michael Eckmann.
Visual C++ Programming: Concepts and Projects
Chapter 6: Arrays Java Software Solutions for AP* Computer Science
Simple Sorting Algorithms
Searching and Sorting SLA Computer Science 4/16/08 Allison Mishkin.
Chapter 3: Sorting and Searching Algorithms 3.2 Simple Sort: O(n 2 )
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
CS 1400 March 30, 2007 Chapter 8 Searching and Sorting.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
CS 106 Introduction to Computer Science I 03 / 08 / 2010 Instructor: Michael Eckmann.
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Algorithm Efficiency and Sorting
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Chapter 8 Arrays and Strings
Programming Logic and Design Fourth Edition, Comprehensive
Searching and Sorting Arrays
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
1 Two-Dimensional Arrays. 2 Can be visualized as consisting m rows, each of n columns Syntax: datatype arrayname [row] [ column] ; Example: int val[3]
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
- SEARCHING - SORTING.  Given:  The array  The search target: the array element value we are looking for  Algorithm:  Start with the initial array.
CSE 1301 J Lecture 13 Sorting Richard Gesick. CSE 1301 J 2 of 30 Sorting an Array When an array's elements are in random order, our Sequential Search.
1 Data Structures and Algorithms Sorting. 2  Sorting is the process of arranging a list of items into a particular order  There must be some value on.
Page 1 Data Structures in C for Non-Computer Science Majors Kirs and Pflughoeft Searching and Sorting Chapter 9.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
+ ARRAYS - SEARCHING - SORTING Dr. Soha S. Zaghloul updated by Rasha M. AL_Eidan 2015.
CSE 373 Data Structures and Algorithms
Lecture 6 Sorting Algorithms: Bubble, Selection, and Insertion.
CS 108 Computing Fundamentals Notes for Thursday, February 19, 2015.
Sorting. Algorithms Sorting reorders the elements in an array or list in either ascending or descending order. Sorting reorders the elements in an array.
BUBBLE SORT. Introduction Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to.
1 2. Program Construction in Java. 2.9 Sorting 3 The need Soritng into categories is relatively easy (if, else if, switch); here we consider sorting.
Lecture -3 on Data structures Array. Prepared by, Jesmin Akhter, Lecturer, IIT, JU Array Data structures are classified as either linear or nonlinear.
Fundamentals of Algorithms MCS - 2 Lecture # 15. Bubble Sort.
12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Sorting Many computer applications.
The Bubble Sort by Mr. Dave Clausen La Cañada High School.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
3 – SIMPLE SORTING ALGORITHMS
Sorting and Searching. Selection Sort  “Search-and-Swap” algorithm 1) Find the smallest element in the array and exchange it with a[0], the first element.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
SORTING ALGORITHMS King Saud University College of Applied studies and Community Service CSC 1101 By: Nada Alhirabi 1.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Review Sorting algorithms Selection Sort Insertion Sort Bubble Sort Merge Sort Quick Sort.
Sorting Sorting takes an unordered array and makes it an ordered one
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
CS 108 Computing Fundamentals Notes for Thursday, February 18, 2016.
12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 1 Simple Searching Many.
UNIT - IV SORTING By B.Venkateswarlu Dept of CSE.
The Bubble Sort Mr. Dave Clausen La Cañada High School
Chapter 9: Sorting and Searching Arrays
Shuttle Sort Example 1st pass Comparisons: 1
CS Two Basic Sorting Algorithms Review Exchange Sorting Merge Sorting
Sorting … and Insertion Sort.
Simple Sorting Methods: Bubble, Selection, Insertion, Shell
Sorting "There's nothing in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The Sorting Hat, Harry Potter.
Searching.
Shuttle Sort Example 1st pass Comparisons: 1
Sorting.
Presentation transcript:

CS 108 Notes for March 1, 2016

#include //My file 1.c int main (void) { char c = 'z' ; char c_array [10] ; int i = 666 ; int i_array [10] ; float f = ; float f_array [10] ; double d = ; double d_array [10] ; printf ("\n Size of char variable c = %d byte.", sizeof(c) ) ; printf ("\n Size of int variable i = %d bytes. ", sizeof(i) ) ; printf ("\n Size of float variable f = %d bytes.", sizeof(f) ) ; printf ("\n Size of double variable d = %d bytes.", sizeof(d) ) ; printf ("\n Size of c_array (10 char elements) = %d bytes.", sizeof(c_array) ) ; printf ("\n Size of i_array (10 int elements) = %d bytes.", sizeof(i_array) ) ; printf ("\n Size of f_array (10 float elements) = %d bytes.", sizeof(f_array) ) ; printf ("\n Size of d_array (10 double elements) = %d bytes.", sizeof(d_array) ) ; printf ("\n\n\n" ) ; return (0) ; } Size of Data Types and Arrays

#include // My file 2.c int main (void) { int index = 0 ; char c = 'z' ; char c_array [10] ; int i = 666 ; int i_array [10] ; float f = ; float f_array [10] ; double d = ; double d_array [10] ; printf ("\nMemory location of char variable c = %p ", &c ) ; printf ("\nMemory location of int variable i = %p ", &i ) ; printf ("\nMemory location of float variable f = %p ", &f ) ; printf ("\nMemory location of double variable d = %p \n\n\n", &d ) ; for (index = 0 ; index < 10 ; index++) printf ("\nMemory location of c_array [ %d ] = %p ", index, &c_array[index] ) ; printf ("\n\n") ; for (index = 0 ; index < 10 ; index++) printf ("\nMemory location of i_array [ %d ] = %p ", index, &i_array[index] ) ; printf ("\n\n\n") ; return (0) ; } Size and Addresses of Data Types and Arrays

The next slide is a graphic representation of the locations in memory of the single variables and some of the arrays found in program 2.c on the previous slide Each "slot" on the next slide represents a byte of memory (bytes are addressable) The addresses listed are just the last four hexadecimal values of the 12 hexadecimal values used to more easily present the 48-bit addressing used on Fang Notice the "space" required by different data types Size and Addresses of Data Types and Arrays

eafbVariable c eafa eaf9 eaf8 eaf7 eaf6 eaf5 eaf4Variable i eaf3 eaf2 eaf1 eaf0Variable f eaef eaee eaed eaec eaeb eaea eae9 eae8Variable d eae7c_array[9] eae6c_array[8] eae5c_array[7] eae4c_array[6] eae3c_array[5] eae2c_array[4] eae1c_array[3] eae0c_array[2] eadfc_array[1] eadec_array[0] eadd eadc eadb eada ead9 ead8i_array[9] ead7 ead6 ead5 ead4i_array[8] ead3 ead2 ead1 ead0i_array[7] eacf eace eacd eacci_array[6] eacb eaca eac9 eac8i_array[5] eac7 eac6 eac5 eac4i_array[4] eac3 eac2 eac1 eac0i_array[3] eabf eabe eabd

Sorting Arrays Many times we will want all the info in an array sorted (which mean ordered) A variety of ways to do this… let's look at accomplishing this as a series of simple tasks. "Chalk talk"

Bubble Sort Adjacent pairs of elements in an array are compared and put into proper order. The first two elements are compared and exchanged if the second is smaller of the two (they are put in order). The value of the next adjacent pair of elements compared and exchanged if necessary (again, put in order). The sequence is repeated until the last two elements of the array have been compared. This sequence of comparisons happens n-1 times for n elements… each sequence of comparisons is called a pass.

Bubble Sort This: (1 st Pass) First pair-wise comparison: Result of first pair-wise comparison: Second pair-wise comparison: Result of second pair-wise comparison: Third pair-wise comparison: Result of third pair-wise comparison: Fourth pair-wise comparison: Result of fourth pair-wise comparison: First pass is now complete… on to pass #2 Question: how would we accomplish this swap?

Bubble Sort This: (2 nd Pass) First pair-wise comparison: Result of first pair-wise comparison: Second pair-wise comparison: Result of second pair-wise comparison: Third pair-wise comparison: Result of third pair-wise comparison: Fourth pair-wise comparison: Result of fourth pair-wise comparison: Second pass is now complete… on to pass #3

Bubble Sort This: (3 rd Pass) First pair-wise comparison: Result of first pair-wise comparison: Second pair-wise comparison: Result of second pair-wise comparison: Third pair-wise comparison: Result of third pair-wise comparison: Fourth pair-wise comparison: Result of fourth pair-wise comparison: Third pass is now complete… on to pass #4

Bubble Sort This: (4 th Pass) First pair-wise comparison: Result of first pair-wise comparison: Second pair-wise comparison: Result of second pair-wise comparison: Third pair-wise comparison: Result of third pair-wise comparison: Fourth pair-wise comparison: Result of fourth pair-wise comparison: Fourth pass is now complete… FINISHED!!

Bubble Sort: Completed - Observations First pair-wise comparison: Result of first pair-wise comparison: Second pair-wise comparison: Result of second pair-wise comparison: Third pair-wise comparison: Result of third pair-wise comparison: Fourth pair-wise comparison: Result of fourth pair-wise comparison: Notice: 5 elements required 4 passes… in general, there must be “size – 1” passes

Bubble Sort: Completed - Observations First pair-wise comparison: Result of first pair-wise comparison: Second pair-wise comparison: Result of second pair-wise comparison: Third pair-wise comparison: Result of third pair-wise comparison: Fourth pair-wise comparison: Result of fourth pair-wise comparison: Elements 0 and 1 Elements 1 and 2 Elements 2 and 3 Elements 3 and 4

Bubble Sort: Completed - Observations First pair-wise comparison: Result of first pair-wise comparison: Second pair-wise comparison: Result of second pair-wise comparison: Third pair-wise comparison: Result of third pair-wise comparison: Fourth pair-wise comparison: Result of fourth pair-wise comparison: Pairwise comparisons: “left element” compared to “right element” or “first element” compared to “first + 1 element” Elements 0 and 1 Elements 1 and 2 Elements 2 and 3 Elements 3 and 4

Bubble Sort: Completed - Observations First pair-wise comparison: Result of first pair-wise comparison: Second pair-wise comparison: Result of second pair-wise comparison: Third pair-wise comparison: Result of third pair-wise comparison: Fourth pair-wise comparison: Result of fourth pair-wise comparison: Pairwise comparisons: “first element” incremented by 1 therefore “first element + 1” also incremented by 1 Elements 0 and 1 Elements 1 and 2 Elements 2 and 3 Elements 3 and 4

Bubble Sort: Completed - Observations First pair-wise comparison: Result of first pair-wise comparison: Second pair-wise comparison: Result of second pair-wise comparison: Third pair-wise comparison: Result of third pair-wise comparison: Fourth pair-wise comparison: Result of fourth pair-wise comparison: Pairwise comparisons: 5 elements and 4 comparisons… in general, there must be “size – 1” comprisons Elements 0 and 1 Elements 1 and 2 Elements 2 and 3 Elements 3 and 4

We need to keep track of two things to accomplish a bubble sort: –We need to keep track of the “passes” via an index starting with 1 and ending at index < size ) –We need to keep track of the “pairwise comparisons” Via another index starting with 0 and ending at index < size – 1) Therefore, we need to know the size of the array (number of elements) to accomplish “size – 1” passes and “size – 1” pairwise comparisons Bubble Sort: Completed - Observations

We’ll need to incorporate the 3 way switch –We’ll need a local variable to as a temporary holding space To track passes we need a pass counter that doesn’t increment until all the pairwise comparisons have been accomplished To track pairwise comparisons we’ll need a pairwise comparison index Pass counter is the outer loop, pairwise comparison index is the inner loop Bubble Sort: Completed - Observations

#include #define SIZE 5 int main ( void ) //3.c { //p_c: pass_counter… left_ele: left element int index = 0 ; int qwerty [ SIZE ] = { 8, 4, 7, 2, 3 } ; int temp = 0 ; //temporary variable used in 3-way exchange int p_c = 0; //counts the passes through the array (need n - 1) int left_ele = 0 ; // facilitates pairwise comparisons (need n – 1) for ( p_c = 1 ; p_c < SIZE ; p_c++ ) // need n - 1 passes { for ( left_ele = 0 ; left_ele < SIZE - 1 ; left_ele++ ) { // need n - 1 pairwise comparisons… starting at 0 if ( qwerty[ left_ele ] > qwerty [ left_ele + 1 ] ) { // 3-way exchange is accomplished, if necessary temp = qwerty[ left_ele ] ; qwerty[ left_ele ] = qwerty[ left_ele + 1 ] ; qwerty[ left_ele + 1 ] = temp ; } for ( index = 0 ; index < SIZE ; index++ ) printf( "\n%d\n", qwerty[ index ] ) ; return ; }

//p_c: pass_counter… left_ele: left element Initial element values/positions in qwerty[ ] : SIZE : temp : p_c : left_ele : qwerty[ left_ele ] : qwerty[ left_ele + 1 ] : Bubble Sort Example

Selection Sort The selection sort process is pretty straightforward: find the unsorted position in a list with the smallest value and swap it with the value found in the first unsorted position in the list. Example, suppose we have the following list of integer values: Step 1 Since 2 is the smallest unsorted item, and since there hasn’t been a swap yet, swap 2 with 8 because 8 is the first item on the list. This leaves:

Selection Sort Step We now consider 2 to be “sorted.” Since 3 is the smallest unsorted item, and because 4 is the first unsorted item on the list, swap 3 with 4. This leaves: Step Now we consider 2 and 3 to be sorted. Since 4 is the smallest unsorted item, and because 7 is the first unsorted item on the list, swap 4 with 7. This leaves:

Selection Sort Step We now consider 2, 3, and 4 to be sorted. Since 7 is the smallest unsorted item, and because 8 is the first unsorted item on the list, swap 8 with 7. This leaves: (a sorted list) Replace “process” with “algorithm”, replace “list” with “array” and replace “item” with “array element” and you have the selection sort algorithm for an array The selection sort algorithm is pretty straightforward: find the unsorted array element with the smallest value and swap it with the value found in the first unsorted array element.

Selection Sort The following slides appear “busy” but that “busy- ness” is due to long identifier names and copious comments To truly understand the selection sort and bubble sort (or any algorithm), you must really study it and trace it until you master it Use the following slides on sorting to help you master these two sorting algorithms

void selection_sort (int passed_array[ ], int n) // n: size of the passed_array { int qwerty [ SIZE ] = { 8, 4, 7, 2, 3 } ; int pos_first; //position of the first unsorted element int pos_other ; //position of other unsorted elements int pos_min_value; //position of the minimum unsorted element int min_value; //value of minimum unsorted element int temp; //temporary variable necessary for 3-way exchange for (pos_first = 0; pos_first < SIZE ; pos_first++) { // increment of outer loop moves pos_first_unsorted_ele forward 1 element in array min_value = qwerty[ pos_first ]; pos_min_value = pos_first ; for ( pos_other = pos_first + 1; pos_other < SIZE ; pos_other++) { // inner for loop finds the lowest value (and it’s element position) to swap if qwerty[ pos_other ] < min_value ) { //testing to find the lowest value and it’s postion in the array min_value = qwerty[ pos_other ] ; pos_of_min_value = pos_other ; } temp = qwerty[ pos_first ] ; qwerty[ pos_first ] = min_value; qwerty[ pos_min_value] = temp; } // once the lowest value and it’s postion are found, it’s swapped (3-way } // exchange) with the value in the first unsorted position (three lines of code above)

#include #define SIZE 5 int main ( void ) //4.c { int qwerty [ SIZE ] = { 8, 4, 7, 2, 3 }, index = 0; int pos_first; //position of the first unsorted element int pos_other ; //position of other unsorted elements int pos_min_value; //position of the minimum unsorted element int min_value; //value of minimum unsorted element int temp; //temporary variable necessary for 3-way exchange for (pos_first = 0; pos_first < SIZE ; pos_first++) { // increment of outer loop moves pos_first_unsorted_ele forward 1 element in array min_value = qwerty[ pos_first ]; pos_min_value = pos_first ; for ( pos_other = pos_first + 1; pos_other < SIZE ; pos_other++) { // inner for loop finds the lowest value (and it’s element position) to swap if ( qwerty[ pos_other ] < min_value ) { //testing to find the lowest value and it’s postion in the array min_value = qwerty[ pos_other ] ; pos_min_value = pos_other ; } temp = qwerty[ pos_first ] ; qwerty[ pos_first ] = min_value; qwerty[ pos_min_value] = temp; } for ( index = 0 ; index < SIZE ; index++ ) printf( "\n%d\n", qwerty[ index ] ) ; return ; }

Initial element positions in passed_array[ ] : SIZE: pos_first : min_value : pos_min_value : pos_other : qwerty [ pos_other] : temp : qwerty[ pos_first ] : qwerty[ pos_min ] : Selection Sort Example

Start at one end of the array and traverse each element until you get to the other end –While traversing each element, compare your “target value” (the value for which you are searching) with the value stored in each element of the array Searching an Array – Sequential Search

Enumerated Data Types An enumerated data type is a data type with values of your own choosing… different from programmer-defined data types Two way to accomplish this –Use an enum statement –Use typedef and enum statements together

Enumerated Data Types Use an enum statement enum days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } ; … enum days today ; today = Tuesday ; Enumeration name names

Enumerated Data Types Use a typedef and enum together typedef enum days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } DAYS ; … DAYS today ; today = Tuesday ; tag names Enumeration name

Enumerated Data Types Regardless of the method used to create the enumerated data type, if we have declare the variable named today as of type days: DAYS today ; today = Tuesday ; today = Wednesday + 1 ; Note: enumerated values are int values in disguise, so integer arithmetic is allowed Note: order of items in an enumerated list determines their underlying int value beginning with 0 for the first item in the list

Back to Arrays Let’s build a program that determines and displays the "percentage enrollment" by major of each major located in the CS Dept. (In other words, we want to determine and display the breakdown of CS, CIS, NCS, TEL, and AC majors) What do we need to know?

Back to Arrays What do we need to know? –The number of students per major. –Here’s some imaginary data: CS: 200 CIS: 50 NCS: 60 TEL: 30 AC: 5 What’s the best way to store this info?

#include // My file 5.c int main (void) { int cs_enrollment [ 5 ] = {200, 50, 60, 30, 5 } ; float cs_pct [ 5 ] ; int index = 0, total = 0; for ( index = 0 ; index <= 4 ; index = index + 1 ) total = total + cs_enrollment [ index ] ; for ( index = 0 ; index <= 4 ; index = index + 1 ) cs_pct [ index ] = (float) cs_enrollment [ index ] / total ; printf("\n\n\n CS majors comprise %4.2f percent of the CS Dept. ", cs_pct [ 0 ] * 100 ); printf("\n CIS majors comprise %4.2f percent of the CS Dept. ", cs_pct [ 1 ] * 100 ); printf("\n NCS majors comprise %4.2f percent of the CS Dept. ", cs_pct [ 2 ] * 100 ); printf("\n TEL majors comprise %4.2f percent of the CS Dept. ", cs_pct [ 3 ] * 100 ); printf("\n AC majors comprise %4.2f percent of the CS Dept. \n\n\n", cs_pct [ 4 ] * 100 ); return (0) ; }

The hardest part of writing an using this program is keep track in our own minds of which elements in the two arrays correspond to which majors. We can use enumerated data types to help us reduce that confusion typedef enum cs_majors { cs, cis, ncs, tel, ac } CS_MAJORS ; … CS_MAJORS majors ;

#include // My file 6.c typedef enum cs_majors { cs, cis, ncs, tel, ac } CS_MAJORS ; int main (void) { int cs_enrollment [ 5 ] = {200, 50, 60, 30, 5 } ; float cs_pct [ 5 ] ; int total = 0 ; CS_MAJORS major ; for ( major = cs ; major <= ac ; major = major + 1 ) total = total + cs_enrollment [ major ] ; for ( major = cs ; major <= ac ; major = major + 1 ) cs_pct [ major ] = (float) cs_enrollment [ major ] / total ; printf(" \n\n CS majors comprise %f percent of the CS Dept majors. ", cs_pct [ cs ] * 100 ); printf(" \n CIS majors comprise %f percent of the CS Dept majors. ", cs_pct [ cis ] * 100 ); printf("\n NCS majors comprise %f percent of the CS Dept majors. ", cs_pct [ ncs ] * 100 ); printf("\n TEL majors comprise %f percent of the CS Dept majors. ", cs_pct [ tel ] * 100 ); printf("\n AC majors comprise %f percent of the CS Dept Hall majors. ",cs_pct [ ac ] * 100 ); printf("\n\n\n"); return (0) ; }