## C++ || Snippet – How To Find The Minimum & Maximum Of 3 Numbers, Print In Ascending Order

This page will demonstrate how to find the minimum and maximum of 3 numbers. After the maximum and minimum numbers are obtained, the 3 numbers are displayed to the screen in ascending order.

This program uses multiple if-statements to determine equality, and uses 3 seperate int varables to store its data. This program is very basic, so it does not utilize an integer array, or any sorting methods.

NOTE: If you want to find the Minimum & Maximum of numbers contained in an integer array, click here.

``` Find The Minimum & Maximum Of 3 Numbers C++ // ============================================================================ // Author: K Perkins // Date: Apr 29, 2012 // Taken From: http://programmingnotes.org/ // File: min_mid_max.cpp // Description: Demonstrates how to find the minimum & maximum of 3 numbers // ============================================================================ #include <iostream> using namespace std; int main() { // declare variables int a=0; int b=0; int c=0; int max=0; int min=0; int middle=0; // get data from user cout<<"Please enter 3 numbers: "; cin >> a >> b >> c; // display information back to the user cout <<"The numbers you just entered are: "<<a<<" "<<b<<" "<<c<<endl; // check for the highest number if(a > b && a > c) { max = a; } else if(b > a && b > c) { max = b; } else { max = c; } // check for the lowest number if(a < b && a < c) { min = a; } else if(b < a && b < c) { min = b; } else { min = c; } // use the 'min' and 'max' variables from above ^ to find // the 'middle' value if((max == a && min == b) || (max == b && min == a)) { middle = c; } else if((max == b && min == c) || (max == c && min == b)) { middle = a; } else { middle = b; } // display data to the screen cout<<"nThe maximum number is: "<<max; cout<<"nThe minimum number is: "<<min; cout<<"nThe numbers in order are: "<<min<<" "<<middle<< " "<<max<<endl; return 0; }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 // ============================================================================//     Author: K Perkins//     Date:   Apr 29, 2012//     Taken From: http://programmingnotes.org///     File:  min_mid_max.cpp//     Description: Demonstrates how to find the minimum & maximum of 3 numbers// ============================================================================#include <iostream>using namespace std; int main(){    // declare variables    int a=0;    int b=0;    int c=0;    int max=0;    int min=0;    int middle=0;        // get data from user    cout<<"Please enter 3 numbers: ";    cin >> a >> b >> c;        // display information back to the user    cout <<"The numbers you just entered are: "<<a<<" "<<b<<" "<<c<<endl;        // check for the highest number    if(a > b && a > c)    {        max = a;    }    else if(b > a && b > c)    {        max = b;    }    else    {        max = c;    }        // check for the lowest number    if(a < b && a < c)    {        min = a;    }    else if(b < a && b < c)    {        min = b;    }    else    {        min = c;    }        // use the 'min' and 'max' variables from above ^ to find    // the 'middle' value    if((max == a && min == b) || (max == b && min == a))    {        middle = c;    }    else if((max == b && min == c) || (max == c && min == b))    {        middle = a;    }    else    {        middle = b;    }        // display data to the screen    cout<<"nThe maximum number is: "<<max;    cout<<"nThe minimum number is: "<<min;    cout<<"nThe numbers in order are: "<<min<<" "<<middle<< " "<<max<<endl;        return 0;}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

```Please enter 3 numbers: 89 56 1987 The numbers you just entered are: 89 56 1987```

``` ```

```The maximum number is: 1987 The minimum number is: 56 The numbers in order are: 56 89 1987 ```

## C++ || “One Size Fits All” – BubbleSort Which Works For Integer, Float, & Char Arrays

Here is another sorting algorithm, which sorts data that is contained in an array. The difference between this method, and the previous methods of sorting data is that this method works with multiple data types, all in one function. So for example, if you wanted to sort an integer and a character array within the same program, the code demonstrated on this page has the ability to sort both data types, eliminating the need to make two separate sorting functions for the two different data types.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

```Integer Arrays Character Arrays BubbleSort Pointers Function Pointers - What Are They? Memcpy Sizeof Sizet Malloc```

``` BubbleSort - One Size Fits All C++ #include <iostream> #include <cstdlib> #include <cctype> #include <iomanip> #include <cstring> #include <ctime> using namespace std; // function prototypes void BubbleSort(void* list, size_t nelm, size_t size, int (*cmp) (const void*, const void*)); void Swap(void* a, void* b, size_t width); int IntCompare (const void * a, const void * b); int StrCompare(const void *a, const void *b); int FloatCompare (const void * a, const void * b); // constant variable for int arrays const int NUM_INTS=14; int main() { // seed random number generator srand(time(NULL)); // =================== INT EXAMPLE =================== // int intNumbers[100]; int numInts=0; // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { intNumbers[x] =rand()%100+1; } cout<<"Original values in the int array:n"; // show original data to the user for(int x=0; x<NUM_INTS; ++x) { cout << setw(4) << intNumbers[x]; } // this is the function call, which takes in an // integer array for sorting purposes // NOTICE: the function "IntCompare" is being used as a parameter BubbleSort(intNumbers,NUM_INTS,sizeof(int),IntCompare); cout<<"nnThe sorted values in the int array:n"; // display sorted array to user for(int x=0; x<NUM_INTS; ++x) { cout << setw(4) << intNumbers[x]; } // creates a line seperator cout << "n-----------------------------------------------" <<"----------------------------------------n"; // =================== FLOAT EXAMPLE =================== // float floatNumbers[100]; // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { floatNumbers[x] =(rand()%100+1)+(0.5); } cout<<"Original values in the float array:n"; // show original array to user for(int x=0; x<NUM_INTS; ++x) { cout << setw(6) << floatNumbers[x]; } // this is the function call, which takes in a // float array for sorting purposes // NOTICE: the function "FloatCompare" is being used as a parameter BubbleSort(floatNumbers,NUM_INTS,sizeof(float),FloatCompare); cout<<"nnThe sorted values in the float array:n"; // show sorted array to user for(int x=0; x<NUM_INTS; ++x) { cout << setw(6) << floatNumbers[x]; } // creates a line seperator cout << "n-----------------------------------------------" <<"----------------------------------------n"; // =================== CHAR EXAMPLE =================== // char* names[100]={"This", "Is","Random","Text","Brought","To", "You","By","My","Programming","Notes"}; int numNames=11; cout<<"Original values in the char array:n"; // show original array to user for(int x=0; x<numNames; ++x) { cout << " " << names[x]; } // this is the function call, which takes in a // char array for sorting purposes // NOTICE: the function "StrCompare" is being used as a parameter BubbleSort(names,numNames,sizeof(char*),StrCompare); cout<<"nnThe sorted values in the char array:n"; // show sorted array to user for(int x=0; x<numNames; ++x) { cout << " " << names[x]; } cout<<endl; return 0; }// end of main void BubbleSort(void* arry, size_t nelm, size_t size, int (*cmp) (const void*, const void*)) {// this function sorts the received array bool sorted = false; do{ sorted = true; for(unsigned int x=0; x < nelm-1; ++x) { if(cmp((((char*)arry)+(x*size)), (((char*)arry)+((x+1)*size))) > 0) { Swap((((char*)arry)+((x)*size)), (((char*)arry)+((x+1)*size)),size); sorted=false; } } --nelm; }while(!sorted); }// end of BubbleSort void Swap(void* a, void* b, size_t width) {// this function swaps the values in the array void *tmp = malloc(width); memcpy(tmp, a, width); memcpy(a, b, width); memcpy(b, tmp, width); free(tmp); }// end of Swap int FloatCompare (const void * a, const void * b) {// this function compares two float values together return (*(float*)a - *(float*)b); }// end of FloatCompare int IntCompare (const void * a, const void * b) {// this function compares two int values together return (*(int*)a - *(int*)b); }// end of IntCompare int StrCompare(const void *a, const void *b) {// this function compares two char values together return(strcmp(*(const char **)a, *(const char **)b)); }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157 #include <iostream>#include <cstdlib>#include <cctype>#include <iomanip>#include <cstring>#include <ctime>using namespace std; // function prototypesvoid BubbleSort(void* list, size_t nelm, size_t size, int (*cmp) (const void*, const void*));void Swap(void* a, void* b, size_t width);int IntCompare (const void * a, const void * b);int StrCompare(const void *a, const void *b);int FloatCompare (const void * a, const void * b); // constant variable for int arraysconst int NUM_INTS=14; int main(){ // seed random number generator srand(time(NULL));  // ===================    INT EXAMPLE    =================== // int intNumbers[100]; int numInts=0;   // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { intNumbers[x] =rand()%100+1; }   cout<<"Original values in the int array:n"; // show original data to the user for(int x=0; x<NUM_INTS; ++x) { cout << setw(4) << intNumbers[x]; } // this is the function call, which takes in an // integer array for sorting purposes // NOTICE: the function "IntCompare" is being used as a parameter BubbleSort(intNumbers,NUM_INTS,sizeof(int),IntCompare); cout<<"nnThe sorted values in the int array:n"; // display sorted array to user for(int x=0; x<NUM_INTS; ++x) { cout << setw(4) << intNumbers[x]; }  // creates a line seperator cout << "n-----------------------------------------------" <<"----------------------------------------n"; // ===================    FLOAT EXAMPLE    =================== // float floatNumbers[100];  // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { floatNumbers[x] =(rand()%100+1)+(0.5); } cout<<"Original values in the float array:n"; // show original array to user for(int x=0; x<NUM_INTS; ++x) { cout << setw(6) << floatNumbers[x]; } // this is the function call, which takes in a // float array for sorting purposes // NOTICE: the function "FloatCompare" is being used as a parameter BubbleSort(floatNumbers,NUM_INTS,sizeof(float),FloatCompare); cout<<"nnThe sorted values in the float array:n"; // show sorted array to user for(int x=0; x<NUM_INTS; ++x) { cout << setw(6) << floatNumbers[x]; } // creates a line seperator cout << "n-----------------------------------------------" <<"----------------------------------------n";  // ===================    CHAR EXAMPLE    =================== // char* names[100]={"This", "Is","Random","Text","Brought","To", "You","By","My","Programming","Notes"}; int numNames=11;   cout<<"Original values in the char array:n"; // show original array to user for(int x=0; x<numNames; ++x) { cout << " " << names[x]; } // this is the function call, which takes in a // char array for sorting purposes // NOTICE: the function "StrCompare" is being used as a parameter BubbleSort(names,numNames,sizeof(char*),StrCompare); cout<<"nnThe sorted values in the char array:n"; // show sorted array to user for(int x=0; x<numNames; ++x) { cout << " " << names[x]; } cout<<endl;  return 0;}// end of main void BubbleSort(void* arry, size_t nelm, size_t size, int (*cmp) (const void*, const void*)){// this function sorts the received array bool sorted = false; do{ sorted = true; for(unsigned int x=0; x < nelm-1; ++x) { if(cmp((((char*)arry)+(x*size)), (((char*)arry)+((x+1)*size))) > 0) { Swap((((char*)arry)+((x)*size)), (((char*)arry)+((x+1)*size)),size); sorted=false; } } --nelm; }while(!sorted);}// end of BubbleSort  void Swap(void* a, void* b, size_t width){// this function swaps the values in the array void *tmp = malloc(width); memcpy(tmp, a, width); memcpy(a, b, width); memcpy(b, tmp, width); free(tmp);}// end of Swap int FloatCompare (const void * a, const void * b){// this function compares two float values together return (*(float*)a - *(float*)b);}// end of FloatCompare int IntCompare (const void * a, const void * b){// this function compares two int values together return (*(int*)a - *(int*)b);}// end of IntCompare int StrCompare(const void *a, const void *b){// this function compares two char values together  return(strcmp(*(const char **)a, *(const char **)b));}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

Notice, the same function declaration is being used for all 3 different data types, with the only difference between each function call are the parameters which are being sent out.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output
(Note: The function works for all three data types)

``` Original values in the int array: 44 91 43 22 20 100 77 80 84 60 47 91 51 81```

``` The sorted values in the int array: 20 22 43 44 47 51 60 77 80 81 84 91 91 100 --------------------------------------------------------------------------------------- Original values in the float array: 49.5 30.5 67.5 50.5 29.5 89.5 78.5 80.5 54.5 7.5 54.5 38.5 56.5 70.5 The sorted values in the float array: 7.5 29.5 30.5 38.5 49.5 50.5 54.5 54.5 56.5 67.5 70.5 78.5 80.5 89.5 --------------------------------------------------------------------------------------- Original values in the char array: This Is Random Text Brought To You By My Programming Notes ```

```The sorted values in the char array: Brought By Is My Notes Programming Random Text This To You ```

## C++ || Snippet – Bubble Sort, Selection Sort, Insertion Sort, Quick Sort & Merge Sort Sample Code For Integer Arrays

This page consists of algorithms for sorting integer arrays. Highlighted on this page are Bubble Sort, Selection Sort, Insertion Sort, Quick Sort, and Merge Sort.

In terms of performance and speed, the sorting algorithms on this page will be listed from the (on average) worst, to best case implementations.

Selection sort and Insertion sort are two simple sorting algorithms which are often more efficient than Bubble Sort, though all three techniques aren’t the top of the class algorithmically for sorting large data sets.

====== BUBBLE SORT ======

``` #1 - Modified Bubble Sort C++ #include <iostream> #include <iomanip> #include <ctime> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototype void BubbleSort(int arry[], int arraySize); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand()%100+1; } cout << "Original array values" << endl; // output the original array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "n--------------------------------------------------------n"; BubbleSort(arry, NUM_INTS); cout << "The current sorted array" << endl; // output the current sorted array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout<<endl; return 0; }// end of main void BubbleSort(int arry[], int arraySize) { bool sorted = false; do{ sorted = true; for(int x = 0; x < arraySize-1; ++x) { if(arry[x] > arry[x+1]) { int temp = arry[x]; arry[x] = arry[x+1]; arry[x+1] = temp; sorted = false; } }// end of for loop --arraySize; }while(!sorted); }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 #include <iostream>#include <iomanip>#include <ctime>#include <cstdlib>using namespace std; // const intconst int NUM_INTS = 12; // function prototypevoid BubbleSort(int arry[], int arraySize); int main(){     // variable declarations     int arry[NUM_INTS];     srand(time(NULL));      // place random numbers into the array     for(int x = 0; x < NUM_INTS; ++x)     {          arry[x] = rand()%100+1;     }       cout << "Original array values" << endl;     // output the original array values     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }     // creates a line seperator      cout << "n--------------------------------------------------------n";      BubbleSort(arry, NUM_INTS);      cout << "The current sorted array" << endl;     // output the current sorted array values     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }     cout<<endl;      return 0;}// end of main void BubbleSort(int arry[], int arraySize){     bool sorted = false;          do{          sorted = true;          for(int x = 0; x < arraySize-1; ++x)          {               if(arry[x] > arry[x+1])               {                    int temp = arry[x];                    arry[x] = arry[x+1];                    arry[x+1] = temp;                    sorted = false;               }           }// end of for loop          --arraySize;     }while(!sorted);}// http://programmingnotes.org/ ```

SAMPLE OUTPUT
(The following randomly generated list took 66 loop iterations/comparisons to sort)

```Original array values 91 65 53 93 54 41 69 76 55 90 10 62 -------------------------------------------------------- The current sorted array 10 41 53 54 55 62 65 69 76 90 91 93```

====== SELECTION SORT ======

``` #2 - Selection Sort C++ #include <iostream> #include <iomanip> #include <ctime> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototype void SelectionSort(int arry[], int arraySize); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand()%100+1; } cout << "Original array values" << endl; // output the original array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "n--------------------------------------------------------n"; SelectionSort(arry, NUM_INTS); cout << "The current sorted array" << endl; // output the current sorted array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout<<endl; return 0; }// end of main void SelectionSort(int arry[], int arraySize) { for(int currentNumber = 0; currentNumber < arraySize; ++currentNumber) { int index_of_min = currentNumber; for(int previousNumber = currentNumber+1; previousNumber < NUM_INTS; ++previousNumber) { if(arry[index_of_min]>arry[previousNumber]) { index_of_min = previousNumber; } } int temp = arry[currentNumber]; arry[currentNumber] = arry[index_of_min]; arry[index_of_min] = temp; } }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 #include <iostream>#include <iomanip>#include <ctime>#include <cstdlib>using namespace std; // const intconst int NUM_INTS = 12; // function prototypevoid SelectionSort(int arry[], int arraySize); int main(){     // variable declarations     int arry[NUM_INTS];     srand(time(NULL));      // place random numbers into the array     for(int x = 0; x < NUM_INTS; ++x)     {          arry[x] = rand()%100+1;     }       cout << "Original array values" << endl;     // output the original array values     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }     // creates a line seperator      cout << "n--------------------------------------------------------n";      SelectionSort(arry, NUM_INTS);      cout << "The current sorted array" << endl;     // output the current sorted array values     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }     cout<<endl;      return 0;}// end of main void SelectionSort(int arry[], int arraySize){ for(int currentNumber = 0; currentNumber < arraySize; ++currentNumber) { int index_of_min = currentNumber; for(int previousNumber = currentNumber+1; previousNumber < NUM_INTS; ++previousNumber) { if(arry[index_of_min]>arry[previousNumber]) { index_of_min = previousNumber; } } int temp = arry[currentNumber]; arry[currentNumber] = arry[index_of_min]; arry[index_of_min] = temp; }}// http://programmingnotes.org/ ```

SAMPLE OUTPUT
(The following randomly generated list took 78 loop iterations/comparisons to sort)

```Original array values 87 74 58 64 4 43 23 16 3 93 9 80 -------------------------------------------------------- The current sorted array 3 4 9 16 23 43 58 64 74 80 87 93```

====== INSERTION SORT ======

``` #3 - Insertion Sort C++ #include <iostream> #include <iomanip> #include <ctime> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototype void InsertionSort(int arry[], int arraySize); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand()%100+1; } // output the original array values cout << "Original array values" << endl; for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "n--------------------------------------------------------n"; InsertionSort(arry, NUM_INTS); // display sorted values cout<<"The current sorted array"<<endl; // output the current sorted array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) <<arry[x]; } cout<<endl; return 0; }// end of main void InsertionSort(int arry[], int arraySize) { int previousNumber = 0; int currentNumber = 0; // iterate through entire list for(int index = 1; index < arraySize; ++index) { currentNumber = arry[index]; previousNumber = index - 1; while(previousNumber >= 0 && arry[previousNumber] > currentNumber) { arry[previousNumber + 1] = arry[previousNumber]; previousNumber = previousNumber - 1; }// end while loop arry[previousNumber + 1] = currentNumber; }// end for loop }// http://programmingnotes.org/ 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 #include <iostream>#include <iomanip>#include <ctime>#include <cstdlib>using namespace std; // const intconst int NUM_INTS = 12; // function prototypevoid InsertionSort(int arry[], int arraySize); int main(){     // variable declarations     int arry[NUM_INTS];     srand(time(NULL));      // place random numbers into the array     for(int x = 0; x < NUM_INTS; ++x)     {          arry[x] = rand()%100+1;     }           // output the original array values     cout << "Original array values" << endl;     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }      // creates a line seperator      cout << "n--------------------------------------------------------n";      InsertionSort(arry, NUM_INTS);      // display sorted values     cout<<"The current sorted array"<<endl;      // output the current sorted array values     for(int x = 0; x < NUM_INTS; ++x)     { cout << setw(4) <<arry[x];     }     cout<<endl;      return 0;}// end of main void InsertionSort(int arry[], int arraySize){ int previousNumber = 0; int currentNumber = 0; // iterate through entire list for(int index = 1; index < arraySize; ++index) { currentNumber = arry[index]; previousNumber = index - 1; while(previousNumber >= 0 && arry[previousNumber] > currentNumber) { arry[previousNumber + 1] = arry[previousNumber]; previousNumber = previousNumber - 1; }// end while loop arry[previousNumber + 1] = currentNumber; }// end for loop}// http://programmingnotes.org/ ```

SAMPLE OUTPUT
(The following randomly generated list took 41 loop iterations/comparisons to sort)

```Original array values 97 80 94 74 10 38 87 7 87 14 3 97 -------------------------------------------------------- The current sorted array 3 7 10 14 38 74 80 87 87 94 97 97```

====== QUICK SORT ======

Quicksort is one of the fastest sorting algorithms, and is often the best practical choice for sorting, as its average expected running time for large data sets is more efficient than the previously discussed methods.

``` #4 - Quick Sort C++ #include <iostream> #include <ctime> #include <iomanip> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototypes void QuickSort(int arry[], int arraySize); int Partition(int arry[], int arraySize, int pivotIndex); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand()%100+1; } cout << "Original array values" << endl; // output the original array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "n--------------------------------------------------------n"; QuickSort(arry, NUM_INTS); cout << "The current sorted array" << endl; // output the current sorted array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout<<endl; return 0; }// end of main void QuickSort(int arry[], int arraySize) { if(arraySize > 1) { // choose pivot int pivotIndex = rand()%(arraySize-1); // partition the arry and get the new pivot position int newPiviotIndex = Partition(arry, arraySize, pivotIndex); // quick sort the first part QuickSort(arry, newPiviotIndex); // quick sort the second part QuickSort(arry+newPiviotIndex+1, arraySize-newPiviotIndex-1); } }// end of QuickSort int Partition(int arry[], int arraySize, int pivotIndex) { int pivotValue = arry[pivotIndex]; arry[pivotIndex] = arry[arraySize-1]; // swap pivot with last element arry[arraySize-1] = pivotValue; int left = 0; // left index int right = arraySize-2; // right index while(left < right) { // ( < pivot ), pivot, ( >= pivot) while((arry[left] < pivotValue) && (left < right)) { ++left; } while((arry[right] >= pivotValue) && (left < right)) { --right; } if(left < right) { std::swap(arry[left],arry[right]); ++left; --right; } } if(left == right) { if(arry[left] < pivotValue) { ++left; } } arry[arraySize-1] = arry[left]; // move pivot to its final place arry[left] = pivotValue; return left; // return the position of the pivot }// http://programmingnotes.org/ 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 #include <iostream>#include <ctime>#include <iomanip>#include <cstdlib>using namespace std; // const intconst int NUM_INTS = 12; // function prototypesvoid QuickSort(int arry[], int arraySize);int Partition(int arry[], int arraySize, int pivotIndex); int main(){     // variable declarations     int arry[NUM_INTS];     srand(time(NULL));      // place random numbers into the array     for(int x = 0; x < NUM_INTS; ++x)     {          arry[x] = rand()%100+1;     }       cout << "Original array values" << endl;     // output the original array values     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }     // creates a line seperator      cout << "n--------------------------------------------------------n";      QuickSort(arry, NUM_INTS);      cout << "The current sorted array" << endl;     // output the current sorted array values     for(int x = 0; x < NUM_INTS; ++x)     {          cout << setw(4) << arry[x];     }     cout<<endl;      return 0;}// end of main void QuickSort(int arry[], int arraySize) {    if(arraySize > 1)     {        // choose pivot        int pivotIndex = rand()%(arraySize-1);         // partition the arry and get the new pivot position        int newPiviotIndex = Partition(arry, arraySize, pivotIndex);         // quick sort the first part        QuickSort(arry, newPiviotIndex);         // quick sort the second part        QuickSort(arry+newPiviotIndex+1, arraySize-newPiviotIndex-1);     }}// end of QuickSort int Partition(int arry[], int arraySize, int pivotIndex) {    int pivotValue = arry[pivotIndex];    arry[pivotIndex] = arry[arraySize-1]; // swap pivot with last element    arry[arraySize-1] = pivotValue;    int left = 0; // left index    int right = arraySize-2; // right index     while(left < right)     { // ( < pivot ), pivot, ( >= pivot)        while((arry[left] < pivotValue) && (left < right))        {            ++left;        }        while((arry[right] >= pivotValue) && (left < right))        {            --right;        }        if(left < right)         {            std::swap(arry[left],arry[right]);            ++left;            --right;        }    }    if(left == right)    {        if(arry[left] < pivotValue)        {            ++left;        }    }    arry[arraySize-1] = arry[left]; // move pivot to its final place    arry[left] = pivotValue;    return left; // return the position of the pivot}// http://programmingnotes.org/ ```

SAMPLE OUTPUT
(The following randomly generated list took 38 loop iterations/comparisons to sort)

```Original array values 50 94 1 16 51 63 41 17 70 28 6 34 -------------------------------------------------------- The current sorted array 1 6 16 17 28 34 41 50 51 63 70 94```

====== MERGE SORT ======

Merge sort is a fast, stable sorting routine which, in the worst case, does about (on average) 39% fewer comparisons than quick sort.

``` #5 - Merge Sort C++ #include <iostream> #include <iomanip> #include <ctime> #include <cstdlib> using namespace std; // const int const int NUM_INTS = 12; // function prototypes void MergeSort(int arry[], int start, int end); void Merge(int arry[], int leftFirst, int leftLast, int rightFirst, int rightLast); int main() { // variable declarations int arry[NUM_INTS]; srand(time(NULL)); // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand()%100+1; } cout << "Original array values" << endl; // output the original array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "n--------------------------------------------------------n"; MergeSort(arry, 0, NUM_INTS-1); cout << "The current sorted array" << endl; // output the current sorted for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout<<endl; return 0; }// end of main void MergeSort(int arry[], int start, int end) { // no significant comparisons are done during splitting if(start < end) { int midPt = (start+end)/2; MergeSort(arry,start, midPt); MergeSort(arry,midPt+1,end); Merge(arry, start,midPt, midPt+1, end); } }// end of MergeSort void Merge(int arry[], int leftFirst, int leftLast, int rightFirst, int rightLast) { int* tempArray = new int [rightLast]; int index = leftFirst; int saveFirst = leftFirst; while((leftFirst <= leftLast) && (rightFirst <= rightLast)) {// compare and select smallest from two subarrays if(arry[leftFirst] < arry[rightFirst]) { tempArray[index] = arry[leftFirst]; // smallest assigned to temp ++leftFirst; } else { tempArray[index] = arry[rightFirst]; ++rightFirst; } ++index; } while(leftFirst <= leftLast) { tempArray[index] = arry[leftFirst]; ++leftFirst; ++index; } while(rightFirst <= rightLast) { tempArray[index] = arry[rightFirst]; ++rightFirst; ++index; } for(index = saveFirst; index <= rightLast; ++index) {// copies from temp array to the initial array arry[index] = tempArray[index]; } }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 #include <iostream>#include <iomanip>#include <ctime>#include <cstdlib>using namespace std; // const intconst int NUM_INTS = 12; // function prototypesvoid MergeSort(int arry[], int start, int end);void Merge(int arry[], int leftFirst, int leftLast, int rightFirst, int rightLast); int main(){ // variable declarations int arry[NUM_INTS]; srand(time(NULL));  // place random numbers into the array for(int x = 0; x < NUM_INTS; ++x) { arry[x] = rand()%100+1; } cout << "Original array values" << endl; // output the original array values for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } // creates a line seperator cout << "n--------------------------------------------------------n";  MergeSort(arry, 0, NUM_INTS-1); cout << "The current sorted array" << endl; // output the current sorted for(int x = 0; x < NUM_INTS; ++x) { cout << setw(4) << arry[x]; } cout<<endl;  return 0;}// end of main void MergeSort(int arry[], int start, int end){  // no significant comparisons are done during splitting    if(start < end)    {        int midPt = (start+end)/2;           MergeSort(arry,start, midPt);        MergeSort(arry,midPt+1,end);        Merge(arry, start,midPt, midPt+1, end);    }}// end of MergeSort void Merge(int arry[], int leftFirst, int leftLast, int rightFirst, int rightLast){ int* tempArray = new int [rightLast]; int index = leftFirst; int saveFirst = leftFirst; while((leftFirst <= leftLast)  && (rightFirst <= rightLast)) {// compare and select smallest from two subarrays if(arry[leftFirst] < arry[rightFirst]) { tempArray[index]  = arry[leftFirst]; // smallest assigned to temp ++leftFirst; } else { tempArray[index]  = arry[rightFirst]; ++rightFirst; } ++index; } while(leftFirst <= leftLast) { tempArray[index] = arry[leftFirst]; ++leftFirst; ++index; } while(rightFirst <= rightLast) { tempArray[index] = arry[rightFirst]; ++rightFirst; ++index; } for(index = saveFirst; index <= rightLast; ++index) {// copies from temp array to the initial array arry[index] = tempArray[index]; }}// http://programmingnotes.org/ ```

SAMPLE OUTPUT
(The following randomly generated list took 29 loop iterations/comparisons to sort)

```Original array values 18 46 41 30 84 97 54 49 19 32 70 30 -------------------------------------------------------- The current sorted array 18 19 30 30 32 41 46 49 54 70 84 97```

## C++ || Snippet – Sort An Integer Array Using Bubble Sort – Print Each Pass & Total Number Of Swaps

This is a program which has no functionality, but displays the sorting of an integer array through the use of the bubble sort algorithm.

This program sorts the values of a one-dimensional array in ascending order using bubble sort. It also prints the total number of passes thru each iteration

REQUIRED KNOWLEDGE FOR THIS SNIPPET

```Integer Arrays Bubble Sort Setw```

NOTE: On some compilers, you may have to add #include < cstdlib> in order for the code to compile.

``` Bubble Sort - Int Array C++ //============================================================================= // This program sorts the values of a one-dimensional array // in ascending order using the Bubble Sort Algorithm. // It also prints the total number of passes thru each iteration //============================================================================= #include <iostream> #include <iomanip> using namespace std; // const int const int NUM_INTS = 12; // function prototype void BubbleSort(int arry[], int &totalSwaps, int &totalPasses); int main() { // Declarations int arry[NUM_INTS] = { 0, 1, 3, 95, 2, 4, 6, 10, 15, 4, 17, 35}; int totalSwaps=0; int totalPasses=0; cout << "Original array values" << endl; // Output the original array values for( int i = 0; i < NUM_INTS; i++ ) { cout << setw( 4 ) << arry[ i ]; } // creates a line separator cout << "n---------------------------------------------------------------nn"; BubbleSort(arry,totalSwaps,totalPasses); // creates a line separator cout << "---------------------------------------------------------------n"; cout << "The current sorted array" << endl; // Output the current sorted for( int i = 0; i < NUM_INTS; i++ ) { cout << setw( 4 ) << arry[ i ]; } // creates a line separator cout << "n---------------------------------------------------------------n"; // Display some statistics to the user cout << "Total Swaps: " << totalSwaps << endl; cout << "Total Passes: " << totalPasses << "nn"; return 0; }// end of main void BubbleSort(int arry[], int &totalSwaps, int &totalPasses) { int currentSwaps = 0; // Loop to determine amount of passes for( int iteration = 1; iteration < NUM_INTS; iteration++ ) { // Reset variable swaps to zero currentSwaps = 0; // Bubble Sort Algorithm // Sort numbers in ascending order for( int p = 0; p < NUM_INTS - iteration; p++ ) { // if the previous value is bigger than the next // then swap places if(arry[p]> arry[p+1]) { int temp = arry[p]; arry[p] = arry[p+1]; arry[p+1]= temp; currentSwaps++; } } cout << "Array after bubble sort pass #" << iteration << endl; // Display values after each pass for( int x = 0; x < NUM_INTS; x++ ) { cout << setw(4) << arry[x]; } cout << "nn"; // Keeps track of the amount of swaps and passes totalSwaps += currentSwaps; totalPasses++; // If no swaps were made in the last pass, // no need to continue the loop. Sorting complete. if( currentSwaps == 0 ) { break; } }// end of for loop }// http://programmingnotes.org/ 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 //=============================================================================//  This program sorts the values of a one-dimensional array     //  in ascending order using the Bubble Sort Algorithm.    // It also prints the total number of passes thru each iteration//=============================================================================#include <iostream>#include <iomanip>using namespace std; // const intconst int NUM_INTS = 12; // function prototypevoid BubbleSort(int arry[], int &totalSwaps, int &totalPasses); int main(){     // Declarations     int arry[NUM_INTS] = { 0, 1, 3, 95, 2, 4, 6, 10, 15, 4, 17, 35};     int totalSwaps=0;      int totalPasses=0;      cout << "Original array values" << endl;      // Output the original array values     for( int i = 0; i < NUM_INTS; i++ )     {          cout << setw( 4 ) << arry[ i ];     }     // creates a line separator      cout << "n---------------------------------------------------------------nn";      BubbleSort(arry,totalSwaps,totalPasses);      // creates a line separator     cout << "---------------------------------------------------------------n";     cout << "The current sorted array" << endl;      // Output the current sorted     for( int i = 0; i < NUM_INTS; i++ )     {          cout << setw( 4 ) << arry[ i ];     }      // creates a line separator     cout << "n---------------------------------------------------------------n";     // Display some statistics to the user     cout << "Total Swaps: " << totalSwaps << endl;     cout << "Total Passes: " << totalPasses << "nn";      return 0;}// end of main void BubbleSort(int arry[], int &totalSwaps, int &totalPasses){     int currentSwaps = 0;      // Loop to determine amount of passes     for( int iteration = 1; iteration < NUM_INTS; iteration++ )     {          // Reset variable swaps to zero          currentSwaps = 0;           // Bubble Sort Algorithm          // Sort numbers in ascending order          for( int p = 0; p < NUM_INTS - iteration; p++ )          {               // if the previous value is bigger than the next               // then swap places               if(arry[p]> arry[p+1])               {                    int temp = arry[p];                    arry[p] = arry[p+1];                    arry[p+1]= temp;                    currentSwaps++;               }          }           cout << "Array after bubble sort pass #" << iteration << endl;           // Display values after each pass          for( int x = 0; x < NUM_INTS; x++ )          {               cout << setw(4) << arry[x];          }           cout << "nn";           // Keeps track of the amount of swaps and passes          totalSwaps += currentSwaps;          totalPasses++;           // If no swaps were made in the last pass,          // no need to continue the loop. Sorting complete.          if( currentSwaps == 0 )          {               break;          }     }// end of for loop}// http://programmingnotes.org/ ```

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

```Original array values 0 1 3 95 2 4 6 10 15 4 17 35 --------------------------------------------------------------- Array after bubble sort pass #1 0 1 3 2 4 6 10 15 4 17 35 95```

``` Array after bubble sort pass #2 0 1 2 3 4 6 10 4 15 17 35 95 Array after bubble sort pass #3 0 1 2 3 4 6 4 10 15 17 35 95 Array after bubble sort pass #4 0 1 2 3 4 4 6 10 15 17 35 95 ```

```Array after bubble sort pass #5 0 1 2 3 4 4 6 10 15 17 35 95 --------------------------------------------------------------- The current sorted array 0 1 2 3 4 4 6 10 15 17 35 95 --------------------------------------------------------------- Total Swaps: 12 Total Passes: 5 ```