960 likes | 1.12k Views
Chapter 7 - Simple Array Applications. Chapter Objectives: •Obtain a stronger understanding of arrays. Introduce basic string functions. Introduce basic searching functions. Introduce basic sorting functions. Introduce basic file operations. Chapter 7 - Simple Array Applications.
E N D
Chapter 7 - Simple Array Applications • Chapter Objectives: • •Obtain a stronger understanding of arrays. • Introduce basic string functions. • Introduce basic searching functions. • Introduce basic sorting functions. • Introduce basic file operations The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - StrLen int StrLen(char String[]) { int Len=0; while(String[Len] !='\0') Len++; return Len; } The code is fairly straightforward. We initialize the Len variable to 0 and then step through the array until we reach the ‘\0’. Each character except the '\0' is counted and finally the Len variable is returned from the StrLen function. Programmer's Notebook: What do you think would happen if an array of characters were passed to StrLen that was not properly terminated with a ‘\0’? Look at the code. The only termination condition for the while loop is when the current array character equals ‘\0’, so if a ‘\0’ is not found, the loop will continue indefinitely. In reality, eventually as the loop continues it will randomly find a ‘\0’ and terminate. The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Example of Using StrLen #include <stdlib.h> #include <iostream.h> #define StringSize 256 //Assume the StrLen definition is here void main() { char Buffer[StringSize]; char Buffer2[]={"This is another expression"}; cout<<"Enter an expression"<<endl; cin>>Buffer; cout<<"The length of the string you just entered is "<< StrLen(Buffer)<<endl; cout<<"The length of the string with spaces is "<< StrLen(Buffer2)<<endl; } The output is as follows: Enter an expression hello The length of the string you just entered is 5 The length of the string with spaces is 26 The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Example of Using StrLen #include <stdlib.h> #include <iostream.h> #define StringSize 256 //Assume the StrLen definition is here void main() { char Buffer[StringSize]; char Buffer2[]={"This is another expression"}; cout<<"Enter an expression"<<endl; cin>>Buffer; cout<<"The length of the string you just entered is "<< StrLen(Buffer)<<endl; cout<<"The length of the string with spaces is "<< StrLen(Buffer2)<<endl; } Programmer's Notebook: Notice when you run the previous program that 256 is not the answer. 256 is the size of the allocated array, not the size of the string. Also notice that if you include a space (' ') in your string, it is counted just like any other character. The output is as follows: Enter an expression hello The length of the string you just entered is 5 The length of the string with spaces is 26 The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-1 #define StringSize 100 void main() { char Buffer1[StringSize]="1st String"; char Buffer2[StringSize]="Another String"; char Buffer3[StringSize]=""; cout<<"The length of the 1st string is "<<StrLen(Buffer1)<<endl; cout<<"The length of the 2nd string is "<<StrLen(Buffer2)<<endl; cout<<"The length of the 3rd string is "<<StrLen(Buffer3)<<endl; } Output: The length of the 1st string is 10 The length of the 2nd string is 14 The length of the 3rd string is 0 The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - StrCpy Recall from our discussion of arrays that you can not copy the contents of one array to another using an = operator as shown below: int Source[10]={1,2,3,4,5,6,7,8,9,10}; int Destination[10]; Destination=Source; //This does not copy the array x to the array y. To copy strings we need a function similar to the one that we wrote to copy arrays, but we can improve it. The previously implemented function required a third parameter that indicated the size of the array. We could use the function we wrote and calculate the string length with the StrLen function we just wrote, however, we can implement the string copy function (StrCpy) without wasting time calculating unnecessary values. See the following code: //Array Implementation of strcpy void StrCpy(char Destination[], char Source[]) { int StringIndex=0; while(source[StringIndex]!='\0') { Destination[StringIndex]=Source[StringIndex]; StringIndex++; } Destination[StringIndex]='\0'; } The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-2 #define StringSize 40 void main() { char String1[StringSize]; StrCpy(String1, "We are going to implement strings"); cout<<String1; } Output: We are going to implement strings The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-3 #define StringSize 40 void main() { char String1[StringSize]="What will display"; StrCpy(String1, "Maybe this?"); cout<<String1; } Output: Maybe this? The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-4 #define StringSize 40 void main() { char String1[StringSize]="What will display"; StrCpy(String1, "What will output if I type all of this here instead!"); cout<<String1; } Output: No predictable output, not enough space for the string. The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-5 #define StringSize 40 void main() { char String1[StringSize]= "What will output if I type all of this here instead!"; StrCpy(String1, "What will display"); cout<<String1; } Output: No output, not enough room at the time of declaration, therefore a syntax error occurs. The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - StrCmp We can not compare two strings with an == operator as we can with other variables. Instead we need a function to compare two strings. StrCmp will return a 0 if the two strings are equal and a non zero value if the two strings are not equal. The function StrCmp is defined as follows: //Implementation of StrCmp int StrCmp(char String1[], char String2[]) { int StringIndex=0; while((String1[StringIndex]==String2[StringIndex]) && (String1[StringIndex]!='\0')) StringIndex++; return(String1[StringIndex]-String2[StringIndex]); } The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - StrCmp Let's look at how strcmp is used in a program: #include <stdlib.h> #include <iostream.h> #define StringSize 256 //Assume the strlen definition is here void main() { char Buffer1[]={"This is a string"}; char Buffer2[]={"This is a string"}; char Buffer3[]={"This string is different"}; if (StrCmp(Buffer1, Buffer2) != 0) cout<<"The string in Buffer 1 is different than the string in Buffer 2" <<endl; else cout<<"The string in Buffer 1 is the same as the string in Buffer 2" <<endl; if (StrCmp(Buffer1, Buffer3) != 0) cout<<"The string in Buffer 1 is different than the string in Buffer 3" <<endl; else cout<<"The string in Buffer 1 is the same as the string in Buffer 3" <<endl; } Ouput: The string in Buffer 1 is the same as the string in Buffer 2 The string in Buffer 1 is different than the string in Buffer 3 The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-6 void main() { char String1[]="What will display"; char String2[]="WHAT WILL DISPLAY"; if (StrCmp(String1,String2) != 0) cout<<"The strings are different"; else cout<<"The strings are the same"; } Output: The strings are different The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-7 void main() { char String1[]="What will display"; char String2[]="What will display"; if (StrCmp(String1,String2) != 0) cout<<"The strings are different"; else cout<<"The strings are the same"; } Output: The strings are the same The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-8 void main() { char String1[100]="What will display"; char String2[18]="What will display"; if (StrCmp(String1,String2) != 0) cout<<"The strings are different"; else cout<<"The strings are the same"; } Output: The strings are the same The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-9 void main() { char String1[]="What will display"; char String2[]="WHAT WILL DISPLAY"; if (StrCmp(String1,String2)) cout<<"The strings are the same"; else cout<<"The strings are different"; } Output: You might think that the output would be as follows: The strings are different However, you would be wrong. The output is as follows: The strings are the same The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - StrCat The final string function we are going to examine is the string concatenation function (StrCat). This function will append the Source string to the end of the Destination string. It assumes that there is enough room in the Destination string to store the original string and the Source string appended onto it. It also assumes that both strings are null terminated properly. Here is an example of using the StrCat function: char Buffer[256]; StrCpy(Buffer, "The Pittsburgh Steelers are the best"); StrCat(Buffer, ", because they just won the Superbowl!"); cout<<Buffer; The output of the previous program will be as follows: The Pittsburgh Steelers are the best, because they just won the Superbowl! The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - StrCat Now let's look at the implementation: //Array Implementation of StrCat void StrCat(char Destination[],char Source[]) { int Len=0; int StringIndex=0; //calculates the end of the destination string while(Destination[Len]!='\0') Len++; while(Source[StringIndex]!='\0') { Destination[Len+StringIndex]=Source[StringIndex]; StringIndex++; } Destination[Len+StringIndex]='\0'; } The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-10 #define StringSize 40 void main() { char String1[StringSize]="What will display"; char String2[StringSize]="What will display"; StrCat(String1, String2); cout<<String2; } Output: What will this display The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-11 #define StringSize 40 void main() { char String1[StringSize]="What will display"; char String2[StringSize]="What will display"; StrCat(String1, String2); cout<<String1; } Output: What will this displayWhat will this display The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-12 #define StringSize 40 void main() { char String1[StringSize]="What will display if this is "; char String2[StringSize]="appeneded to the first string"; StrCat(String1, String2); cout<<String1; } Output: There would be no predictable output from this drill. When the StrCat function attempts to append the string contained in the array String2 to the string contained in array String1, the amount of space allocated for the array String1 is exeeded. Therefore, a run-time error occurs. The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-13 #define StringSize 40 void main() { char String1[StringSize]; char String2[StringSize]="What will display"; StrCat(String1, String2); cout<<String1; } Output: There would be no predictable output from this drill. When the StrCat function attempts to append the string contained in the array String2 to the string contained in the array String1, we find that there is no valid string contained in array String1. Without a valid string, there is no way for StrCat to determine the proper place to append the string contained in the array String2. Therefore, a run-time error occurs. The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-14 #define StringSize 40 void main() { char String1[StringSize]=""; char String2[StringSize]="What will display"; StrCat(String1, String2); cout<<String1; } Output: What will this display The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Other String Functions StrNCpy It is identical to StrCpy except instead of copying all the contents of the source string to the destination string, it copies the 1st n characters of the source to the destination string. char String1[]="Pittsburgh is great!"; char Buffer[11]; StrNCpy(Buffer,String1,10); cout<<Buffer; The output would be as follows: Pittsburgh StrNCat It works similarly to StrCat, but instead of appending the entire source string to the end of the destination string, it only appends the first n characters of the source string to the destination string. char Buffer[256]; StrCpy(Buffer, "The Pittsburgh Steelers are the best"); StrNCat(Buffer, ", because they just won the Superbowl!", 23); cout<<Buffer; The output would be as follows: The Pittsburgh Steelers are the best, because they just won The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Other String Functions StrNCmp The final function worth implementing is the StrNCmp function. This function is similar to the StrCmp function, but will return a 0 if n characters are the same between the two strings. Otherwise it will return a non-zero number. char Buffer1[]="Pittsburgh won the Superbowl"; char Buffer2[]="Pittsburgh won the playoff game"; if (StrCmp(Buffer1,Buffer2)==0) cout<<"The strings are the same\n"; else cout<<"The strings are different\n"; if (StrNCmp(Buffer1, Buffer2,10)==0) cout<<"The 1st 10 characters are the same\n"; else cout<<"The 1st 10 characters are different\n"; if (StrNCmp(Buffer1, Buffer2,25)==0) cout<<"The 1st 25 characters are the same\n"; else cout<<"The 1st 25 characters are different\n"; The output would be the following: The strings are different The 1st 10 characters are the same. The 1st 25 characters are different. The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Other String Functions Let’s write a function that accepts two parameters, an array of characters and a character to search for in the array of characters. If the character is contained within the array of characters, then the function will return true, otherwise it will return false. //Array Implementation of FindIt bool FindIt(char Array[], char SearchValue) { int Counter=0; bool Found=false; while(Array[Counter] != '\0') { if (Array[Counter] == SearchValue) Found=true; Counter++; } return Found; } The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Drill 7-15 #include <stdlib.h> #include <iostream.h> #include <string.h> //Assume the string defintions are here! void main() { char String1[]="This is the first string"; char String2[]="Yet another string"; char String3[100]; cout<<StrLen(String1)<<endl; cout<<StrLen(String2)<<endl; cout<<StrLen(String3)<<endl; StrCpy(String3,String1); cout<<String3<<endl; StrCat(String3,String2); cout<<String3<<endl; cout<<StrCmp(String2,String2)<<endl; if (StrCmp(String1,String2)) cout<<"The strings are equal"<<endl; else cout<<"The strings are not equal"<<endl; cout<<StrLen(String3)<<endl; } Output: 24 18 error This is the first string This is the first stringYet another string 0 These strings are equal 42 The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Reading Strings With Spaces All of the examples that we have tried so far were picked because they did not have a space in the middle of the string when we obtained it from the user. Try running the following code and enter the string “The Pittsburgh Steelers will be great next year!” //Incorrect cin example #include <stdlib.h> #include <iostream.h> #define MaxStringSize 100 void main() { char Buffer[MaxStringSize]; cout<<"Please enter a string containing a space"<<endl; cin>>Buffer; cout<<Buffer; } You would expect the output to be: The Pittsburgh Steelers will be great next year! Instead you would find the output to be: The The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications String Functions - Reading Strings With Spaces By adding the .getline to the cin command, you are able to pass cin two parameters. The first is the array of characters to store the value entered from the user. The second is the maximum number of characters the user can enter into the array. This is usually set to the size of the array. //Correct cin example #include <stdlib.h> #include <iostream.h> #define MaxStringSize 100 void main() { char Buffer[MaxStringSize]; cout<<"Please enter a string containing a space"<<endl; cin.getline(Buffer,MaxStringSize); cout<<Buffer; } The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications Linear Search - No Assumptions Another important operation we often wish to perform on a list of values stored in an array is to search for a specific value. #include <stdlib.h> #include <iostream.h> #define ArraySize 100 int Array[ArraySize]; //Global Array to be searched void main() { int LoopCounter; int SearchItem; bool FoundFlag=false; //initialize the array somehow //Get the value to search for cout<<"Enter the item to search for"<<endl; cin>>SearchItem; //Search for the value for (LoopCounter=0; LoopCounter<ArraySize;LoopCounter++) if (Array[LoopCounter]==SearchItem) FoundFlag=true; //Check if the value was found if (FoundFlag) cout<<"Item was found"; } The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications Linear Search - Improved Algorithm #include <stdlib.h> #include <iostream.h> #define ArraySize 100 int Array[ArraySize]; //Global Array to be searched void main() { int LoopCounter; int SearchItem; bool FoundFlag=false; //initialize the array somehow //Get the value to search for cout<<"Enter the item to search for"<<endl; cin>>SearchItem; //Search for the value for (LoopCounter=0; ((LoopCounter<ArraySize) && (FoundFlag==false));LoopCounter++) if (Array[ArraySize]==SearchItem) FoundFlag=true; //Check if the value was found if (FoundFlag) cout<<"Item was found"; } The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort One of the easiest sorts is the bubble sort. The reason it is called the bubble sort is that we pass over the values in the array, comparing adjacent elements, and if the value to the left is greater than the value to the right, we swap them. By the end of a pass over the data, the greatest value in the array "bubbles" to the top of the array. As we continually pass over the array, we continually place one more value in the proper place after each pass. If we make the same number of passes over the array as the number of items in the array, then all the elements in the array will be sorted from lowest to highest. Before we look at the code to implement the bubble sort, let's make sure we understand what we wish to accomplish. The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort Lets start with the following list in an array of six integers: 0 1 2 3 4 5 53 13 1 90 120 5 The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort We start by comparing the value in Array[0] to Array[1], or 53 to 13. Since 53 is greater than 13, we swap then. So the array now looks as follows: 0 1 2 3 4 5 13 53 1 90 120 5 The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort But, our work is not done yet, even for the first pass. Now we compare the value in Array[1] to the value in Array[2], or 53 to 1. Since 53 is greater than 1, we swap them and the array looks as follows: 0 1 2 3 4 5 13 1 53 90 120 5 The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort We continue the process and compare Array[2] to Array[3], or 53 to 90. Since 53 is not greater than 90 there is no reason to swap them and the array remains the same as before. 0 1 2 3 4 5 13 1 53 90 120 5 The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort The final check of the 1st pass is Array[3] to Array[4], or 120 to 5. Since 120 > 5, we swap the two values and then array looks as follows: 0 1 2 3 4 5 13 1 53 90 5 120 Guaranteed Sorted The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort Notice, that 120 is in its final position within the array. Depending upon the elements in the array, more than one value might be in the proper place, but only one value, the largest, is guaranteed to be in the proper place. Also notice that in order to compare all the values in the array, we only need N-1 comparisons where n is equal to the number of elements in the array. Now we need to repeat the process until all the values in the array are in the proper order. The following is what the array looks like after each pass of the bubble sort algorithm: After 1 Pass 0 1 2 3 4 5 13 1 53 90 5 120 Guaranteed Sorted The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort Notice, that 120 is in its final position within the array. Depending upon the elements in the array, more than one value might be in the proper place, but only one value, the largest, is guaranteed to be in the proper place. Also notice that in order to compare all the values in the array, we only need N-1 comparisons where n is equal to the number of elements in the array. Now we need to repeat the process until all the values in the array are in the proper order. The following is what the array looks like after each pass of the bubble sort algorithm: After 2 Passes 0 1 2 3 4 5 1 13 53 5 90 120 Guaranteed Sorted The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort Notice, that 120 is in its final position within the array. Depending upon the elements in the array, more than one value might be in the proper place, but only one value, the largest, is guaranteed to be in the proper place. Also notice that in order to compare all the values in the array, we only need N-1 comparisons where n is equal to the number of elements in the array. Now we need to repeat the process until all the values in the array are in the proper order. The following is what the array looks like after each pass of the bubble sort algorithm: After 3 Passes 0 1 2 3 4 5 1 13 5 53 90 120 Guaranteed Sorted The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort Notice that 120 is in its final position within the array. Depending upon the elements in the array, more than one value might be in the proper place, but only one value, the largest, is guaranteed to be in the proper place. Also notice that in order to compare all the values in the array, we only need N-1 comparisons where n is equal to the number of elements in the array. Now we need to repeat the process until all the values in the array are in the proper order. The following is what the array looks like after each pass of the bubble sort algorithm: After 4 Passes 0 1 2 3 4 5 1 5 13 53 90 120 Guaranteed Sorted The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort Notice that although there are 6 elements in the array, we only required 4 passes to completely sort the array. In the worst case we require one less pass than the number of elements. This is because if on each pass we place at least one value in its proper place then after n-1 passes, where n is the number of values in the array, we have n-1 items in place. By default if only one item is left, then it must be in its proper place. Also, if we are writing the most efficient code possible we would want the BubbleSort function to stop once we have the entire array sorted. To improve understanding of the code we are going to review three implementations of the BubbleSort function. All will work, but each one will be more efficient than the previous one. The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort - 1st Version void BubbleSort (int Array[], int NumItems) { int NumPasses; int InnerLoopCounter; int Temp; //Outer loop controlling # of passes for (NumPasses=0; NumPasses<NumItems-1; NumPasses++) // Inner loop controlling # of comparisons per pass for (InnerLoopCounter=0; InnerLoopCounter<NumItems-1; InnerLoopCounter++) // Compare adjacent array values if (Array[InnerLoopCounter] > Array[InnerLoopCounter+1]) { Temp = Array[InnerLoopCounter]; // Perform swap of two adjacent values Array[InnerLoopCounter]=Array[InnerLoopCounter+1]; Array[InnerLoopCounter+1]=Temp; } } The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort - 2nd Version We need another version, because if you stepped through the above code step by step, you would observe comparisons occurring that are unnecessary. We stated that each pass places an item in the proper place, so why should we compare it to anything? We know that no swap will occur. Therefore, we can modify the inner loop by reducing the upper bound of the index by the number of items guaranteed to be in the proper place. void BubbleSort (int Array[], int NumItems) { int NumPasses; int InnerLoopCounter; int Temp; //Outer loop controlling # of passes for (NumPasses=0; NumPasses<NumItems-1; NumPasses++) // Inner loop controlling # of comparisons per pass for (InnerLoopCounter=0; InnerLoopCounter<NumItems-1-NumPasses; InnerLoopCounter++) // Compare adjacent array values if (Array[InnerLoopCounter] > Array[InnerLoopCounter+1]) { Temp = Array[InnerLoopCounter]; // Perform swap of two adjacent values Array[InnerLoopCounter]=Array[InnerLoopCounter+1]; Array[InnerLoopCounter+1]=Temp; } } The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort - 3rd Version While the second version is an improvement, we can easily improve it further. Image if you had an array that was already sorted? The 2nd version would not be very efficient. void BubbleSort (int Array[], int NumItems) { int NumPasses; int InnerLoopCounter; int Temp; bool SwapOccurred = true; //Outer loop controlling # of passes for (NumPasses=0; ((NumPasses<NumItems-1) && (SwapOccurred==true)); NumPasses++) { SwapOccurred=false; for (InnerLoopCounter=0; InnerLoopCounter<NumItems-1; // Inner loop controlling # of comparisons per pass InnerLoopCounter++) // Compare adjacent array values if (Array[InnerLoopCounter] > Array[InnerLoopCounter+1]) { SwapOccurred=true; // Perform swap of two adjacent values Temp = Array[InnerLoopCounter]; Array[InnerLoopCounter]=Array[InnerLoopCounter+1]; Array[InnerLoopCounter+1]=Temp; } } } The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort - Drill 7-16 Trace though the BubbleSort function and determine what the following arrays would look like after 1 pass through the outer loop of the BubbleSort function, 2 passes through the outer loop of the bubble sort code, and 3 passes through the outer loop of the bubble sort code. A pass is equivalent to the execution of the inner for loop for a single value of NumPasses. So the 1st pass is when NumPasses=0, the second pass is when NumPasses=1, and the 3rd pass is when NumPasses=2. 0 1 2 3 4 5 13 1 53 90 5 120 The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort - Drill 7-16 Trace though the BubbleSort function and determine what the following arrays would look like after 1 pass through the outer loop of the BubbleSort function, 2 passes through the outer loop of the bubble sort code, and 3 passes through the outer loop of the bubble sort code. A pass is equivalent to the execution of the inner for loop for a single value of NumPasses. So the 1st pass is when NumPasses=0, the second pass is when NumPasses=1, and the 3rd pass is when NumPasses=2. After 1 Pass 0 1 2 3 4 5 5 4 3 2 1 6 Guaranteed Sorted The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort - Drill 7-16 Trace though the BubbleSort function and determine what the following arrays would look like after 1 pass through the outer loop of the BubbleSort function, 2 passes through the outer loop of the bubble sort code, and 3 passes through the outer loop of the bubble sort code. A pass is equivalent to the execution of the inner for loop for a single value of NumPasses. So the 1st pass is when NumPasses=0, the second pass is when NumPasses=1, and the 3rd pass is when NumPasses=2. After 2 Passes 0 1 2 3 4 5 4 3 2 1 5 6 Guaranteed Sorted The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort - Drill 7-16 Trace though the BubbleSort function and determine what the following arrays would look like after 1 pass through the outer loop of the BubbleSort function, 2 passes through the outer loop of the bubble sort code, and 3 passes through the outer loop of the bubble sort code. A pass is equivalent to the execution of the inner for loop for a single value of NumPasses. So the 1st pass is when NumPasses=0, the second pass is when NumPasses=1, and the 3rd pass is when NumPasses=2. After 3 Passes 0 1 2 3 4 5 3 2 1 4 5 6 Guaranteed Sorted The C++ Coach - Essentials for Introductory Programming - 2000
Chapter 7 - Simple Array Applications 7.3 Bubble Sort - Drill 7-16 Trace though the BubbleSort code and determine what the following arrays would look like after each pass through the outer loop of the bubble sort code. 0 1 2 3 4 5 3 120 100 33 142 1 The C++ Coach - Essentials for Introductory Programming - 2000