Data Structure: Storing and Organizing Data Efficiently
E N D
Presentation Transcript
Data Structure(s) • A way of storing and organizing data in a computer so that it can be used efficiently. • e.g. • Arrays • Linked Lists • stacks • Queues • Trees etc
Array • Consecutive group of memory locations • Same name • Same type (int, char, etc.)
Declaring Arrays • When declaring arrays, specify • Type of array • Name • Number of elements • type arrayName[arraySize]; int c[ 10 ]; // array of 10 integers float d[ 3284 ]; // array of 3284 floats • Declaring multiple arrays of same type • Use comma separated list, like regular variables int b[ 100 ], x[ 27 ];
Initializing Arrays • Initializing arrays • For loop • Set each element • Initializer list • Specify each element when array declared int n[ 5 ] = { 1, 2, 3, 4, 5 }; • If not enough initializers, rightmost elements 0 • If too many syntax error
To set every element to 0 int n[ 5 ] = { 0 }; • If array size omitted, Initializer determine size int n[] = { 1, 2, 3, 4, 5 }; • 5 Initializer, therefore 5 element array
Array elements like other variables • Assignment, printing for an integer array c c[ 0 ] = 3; cout << c[ 0 ]; • A subscript must be an integer or integer expression. • Can perform operations inside subscript c[ 5 – 2 ] same as c[3]
To refer to an element • Specify array name and position number (index/subscript) • Format: arrayname[ position number ] • First element at position 0 • N-element array c c[ 0 ], c[ 1 ] … c[ n - 1 ] • Nth element as position N-1
Example #include <iostream> using namespace std; void main() { int n[ 5]={4,5, 6,10,12}; cout<<"Array elements\n"; cout<<n[0]<<endl; cout<<n[1]<<endl; cout<<n[2]<<endl; cout<<n[3]<<endl; cout<<n[4]<<endl; }
Example #include <iostream> using namespace std; void main() { int n[ 10 ]={4,5, 6,10,12}; cout<<"Array elements\n"; for ( int i = 0; i < 5; i++ ) cout<<n[i]<<endl; }
Allow the user to input integers in an array only if the integer is even.
Passing Arrays to Functions • Specify name without brackets • To pass array myArray to myFunction int myArray[ 24 ]; myFunction( myArray, 24 ); • Array size usually passed, but not required • Useful to iterate over all elements
Passing Arrays to Functions • Arrays passed-by-reference • Functions can modify original array data • Value of name of array is address of first element • Function knows where the array is stored • Can change original memory locations • Individual array elements passed-by-value • Like regular variables • square( myArray[3] );
Passing Arrays to Functions • Functions taking arrays • Function prototype • void modifyArray( int b[], int arraySize ); • void modifyArray( int [], int ); • Names optional in prototype • Both take an integer array and a single integer • No need for array size between brackets • Ignored by compiler • If declare array parameter as const • Cannot be modified (compiler error) • void doNotModify( const int [] );
Example (Passing Array to Functions) void function1(int [], int); void function2(int); void main () { const int size=5; int array[]={1, 2,3 ,4,5}; cout<<"Array elements before function call:"; for (int i=0; i<5;i++) cout<<array[i]<<" "; cout<<endl;
function1(array, 5); cout<<endl; cout<<"Array elements after function call\n"; for (i=0; i<size;i++) cout<<array[i]<<" "; cout<<endl; cout<<endl; cout<<"passing array element array[2] to the function\n"; cout<<"Before:"<<array[2]<<endl; function2(array[2]); cout<<"After:"<<array[2]<<endl; }
//function definitions void function1(int a[],int size) { cout<<"Array elements in function call\n"; for (int i=0; i<size; i++) cout<<(a[i]*=2)<<" "; } void function2( int x) { cout<<"In Function:"; cout<<x*2<<endl; }
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
Example (Array Search) #include<iostream> using namespace std; void main () { const int size=10; int a[size]={ 5,6,1,8,3,7,2,10,9,4}; for(int k=0; k<size; k++) cout<<a[k]<<" "; cout<<endl; int searchKey; cout << "Enter integer search key: "; cin >> searchKey;
for( k=0; k<size; k++) if (a[k]==searchKey) cout<<"The element to be searched is found at index a["<<k<<"]"; cout<<endl; }
Sorting Arrays • Sorting data • Important computing application • Virtually every organization must sort some data • Bubble sort • Several passes through the array (assume: elements are to be sorted in increasing order) • Successive pairs of elements are compared • If increasing order (or identical), no change • If decreasing order, elements exchanged • Repeat these steps for every element
Sorting Arrays • Example: • Go left to right, and exchange elements as necessary • One pass for each element Original: 3 4 2 7 6 Pass 1: 3 2 46 7 (elements exchanged) Pass 2: 2 3 4 6 7 Pass 3: 2 3 4 6 7 (no changes needed) Pass 4: 2 3 4 6 7 Pass 5: 2 3 4 6 7
Sorting Arrays • Swapping variables int x = 3, y = 4; y = x; x = y; • What happened? • Both x and y are 3! • Need a temporary variable • Solution int x = 3, y = 4, temp = 0; temp = x; // temp gets 3 x = y; // x gets 4 y = temp; // y gets 3
Example (Array Sorting) #include<iostream> using namespace std; void main () { const int size=10; int a[size]={ 5,6,1,8,3,7,2,10,9,4}; for(int k=0; k<size; k++) cout<<a[k]<<" "; cout<<endl;
int temp; //sorting process for ( int pass = 0; pass < size - 1; pass++ ) for ( int j = 0; j < size - 1; j++ ) // loop to control number of comparisons per pass if ( a[ j ] > a[ j + 1 ] ) { temp = a[ j ]; a[ j ] = a[ j + 1 ]; a[ j + 1 ] = temp; } cout<<"Sorted Array\n"; for( k=0; k<size; k++) cout<<a[k]<<" "; cout<<endl; }
Character Arrays • 2 kinds of strings • C-Strings • Objects of String class
Contd… • Strings • Arrays of characters • All strings end with null ('\0') • Examples • char string1[] = "hello"; • Null character implicitly added • string1 has 6 elements • char string1[] = { 'h', 'e', 'l', 'l', 'o', '\0’ }; • Subscripting is the same String1[ 0 ] is 'h' string1[ 2 ] is 'l'
Contd… • Input from keyboard char string2[ 10 ]; cin >> string2; • Puts user input in string • Stops at first whitespace character • Adds null character • If too much text entered, data written beyond array • Printing strings • cout << string2 << endl; • Does not work for other array types • Characters printed until null found
Example (C-String Variable) #include<iostream> using namespace std; int main () { char a[20]; cout<<"Enter String\n"; cin>>a; cout<<"you entered "<<a<<endl; return 0; }
Example (String Constants) #include<iostream> using namespace std; int main () { char question[] = "Please, enter your first name: "; char greeting[] = "Hello, "; char yourname [80]; cout << question; cin >> yourname; cout << greeting << yourname << "!"<<endl; return 0; }
Example (Reading Embedded Blanks) #include<iostream> using namespace std; int main () { char question[] = "Please, enter your first name: "; char greeting[] = "Hello, "; char yourname [80]; cout << question; cin.get(yourname,80); cout << greeting << yourname << "!"<<endl; return 0; }
Copying string #include <iostream> using namespace std; int main() { char a1[50]="This is a string"; char a2[50]; for (int i=0;a1[i]!='\0'; i++) a2[i]=a1[i]; a2[i]='\0'; cout<<a2<<endl; return 0; }
Easy way! #include <iostream> using namespace std; int main() { char a1[50]="This is a string"; char a2[50]; strcpy(a2,a1); cout<<a2<<endl; return 0; }
strlen, strcpy() & strcmp() • Strlen (array); tells the length of the array • Strcpy(destination, source); Copies the source values to the destination • Strcmp(str1, str2); compares two strings str1 & str2 and gives the integer value. • 0 indicates the matching strings • Otherwise not same
String class • No need to specify array size (responsibility of memory management) • Input and output similar to C-Strings
Example #include<iostream> #include<string> using namespace std; int main () { string question = "Please, enter your first name: "; string greeting ("Hello, "); string yourname; cout << question; getline(cin, yourname); cout<<greeting+yourname<<endl; return 0; }
Column 0 Column 1 Column 2 Column 3 a[ 0 ][ 3 ] a[ 1 ][ 0 ] a[ 2 ][ 3 ] a[ 2 ][ 2 ] a[ 1 ][ 3 ] a[ 0 ][ 0 ] a[ 1 ][ 1 ] a[ 2 ][ 1 ] a[ 0 ][ 2 ] a[ 1 ][ 2 ] a[ 2 ][ 0 ] a[ 0 ][ 1 ] Row 0 Row 1 Row 2 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 Column subscript Array name Row subscript
1 2 3 4 1 0 3 4 Multiple-Subscripted Arrays • To initialize • Initializersgrouped by row in braces int b[ 2 ][ 2 ] = { { 1, 2 }, { 3, 4 } }; int b[ 2 ][ 2 ] = { { 1 }, { 3, 4 } }; Row 0 Row 1
1 0 3 4 Multiple-Subscripted Arrays • Referenced like normal cout << b[ 0 ][ 1 ]; • Outputs 0 • Cannot reference using commas cout << b[ 0, 1 ]; • Syntax error • Function prototypes • Must specify sizes of subscripts • First subscript not necessary, as with single-scripted arrays • void printArray( int [][ 3 ] );
Example //print the total of 2D array elements #include<iostream.h> int main () { int a[3][3]={1,2,3,4,5,6,7,8,9}; cout<<"Array a is:\n"; for (inti=0; i<3;i++) { for (int j=0;j<3;j++) cout<<a[i][j]<<" "; cout<<endl; }
int total=0; for (inti=0; i<3;i++) for (int j=0;j<3;j++) total+= a[i][j]; cout<<“Total of Array elements is:”<<total<<endl return 0; }
Example (Passing 2D Arrays to Functions) #include<iostream.h> void add(int a[3][3], int b[3][3]) { for (inti=0; i<3;i++) { for (int j=0;j<3;j++) cout<<(a[i][j]+b[i][j])<<" "; cout<<endl; } }
int main() { int a[][3]={1,2,3,4,5,6,7,8,9}; int b[][3]={1,2,3,4,5,6,7,8,9}; cout<<"Array a is:\n"; for (inti=0; i<3;i++) { for (int j=0;j<3;j++) cout<<a[i][j]<<" "; cout<<endl; }