Tag Archives: sort
C++ || How To Sort An Array/Vector/Container With Multiple Sorting Conditions Using C++
The following is a module with functions which demonstrates how to sort an array/vector/container with multiple sorting conditions using C++.
The function demonstrated on this page is a wrapper for the std::sort function, which means it works for any container supported by std::sort.
This function accepts multiple sorting conditions (comparison functions), which allows for complex array sorting much like the SQL/LINQ ‘Order By’ operation.
1. Simple Array – Ascending
The example below demonstrates the use of Utils::sortBy to sort a simple array.
In this example, no sorting conditions are specified. In this case, the array is sorted in ascending order.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Simple Array - Ascending // Declare array int arry[] = { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; // Get array size int size = sizeof(arry) / sizeof(arry[0]); // Sort array in default ascending order Utils::sortBy(arry, arry + size); // Display results for (int index = 0; index < size; ++index) { std::cout << arry[index] << std::endl; } // expected output: /* 19 22 28 31 1987 1991 2009 2019 */ |
2. Simple Array – Descending
The example below demonstrates the use of Utils::sortBy to sort a simple array.
In this example, a sorting condition (comparison function) is specified. In this case, the array is sorted in descending order.
Note: In the example below, a lambda is used, though it is not required. A regular function can be used here as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// Simple Array - Descending // Declare array int arry[] = { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; // Get array size int size = sizeof(arry) / sizeof(arry[0]); // Declare sort condition auto condition = [](const auto& lhs, const auto& rhs) { return lhs > rhs; }; // Sort array in descending order Utils::sortBy(arry, arry + size, condition); // Display results for (int index = 0; index < size; ++index) { std::cout << arry[index] << std::endl; } // expected output: /* 2019 2009 1991 1987 31 28 22 19 */ |
3. Object Vector – Multi Key Sort
The example below demonstrates the use of Utils::sortBy to sort an object vector.
In this example, multiple sorting conditions (comparison functions) are specified. In this case, the vector is sorted by multiple object properties.
When multiple sorting conditions are specified, the sequence is sorted in the order in which the conditions are supplied (FIFO).
Note: In the example below, lambda functions are used, though they are not required. Regular functions can be used here as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// Object Vector - Multi Key Sort // Declare object struct Person { int id; std::string name; }; // Declare data std::vector<Person> people = { {31, "Kenneth"}, {28, "Jennifer"}, {87, "Lynn"}, {91, "Sole"}, {22, "Kenneth"}, {19, "Jennifer"} }; // Sort vector by name length ASC, id DESC Utils::sortBy(people.begin(), people.end(), { [](const auto& lhs, const auto& rhs) { return lhs.name.length() < rhs.name.length(); }, [](const auto& lhs, const auto& rhs) { return lhs.id > rhs.id; } }); // Display results for (const auto& person : people) { std::cout << person.id << " - " << person.name << std::endl; } // expected output: /* 91 - Sole 87 - Lynn 31 - Kenneth 22 - Kenneth 28 - Jennifer 19 - Jennifer */ |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
// ============================================================================ // Author: Kenneth Perkins // Date: Mar 8, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <algorithm> #include <functional> #include <type_traits> #include <iterator> #include <vector> namespace Utils { /** * FUNCTION: evaluate * USE: Evaluates each sorting condition and determines the order the item should be in * @param conditions: The comparison functions by which the sequence should be sorted * @param lhs: The first element for comparison * @param rhs: The second element for comparison * @return: The sorting order of this item */ template<typename T> bool evaluate(const std::vector<std::function<bool(T, T)>>& conditions, const T& lhs, const T& rhs) { bool result = false; // Evaluate each condition based on the order they were supplied in for (const auto& condition : conditions) { // Call the comparison function to evaluate the condition if (condition(lhs, rhs)) { result = true; break; } else if (condition(rhs, lhs)) { break; } } return result; } /** * FUNCTION: sortBy * USE: Sorts a sequence in ascending or descending order depending on the sorting conditions * @param first: The first position of the sequence to be sorted * @param last: The last position of the sequence to be sorted * @param conditions: The comparison functions by which the sequence should be sorted. * Accepts multiple comparison functions. The sequence is sorted in the * order in which the conditions were placed (FIFO) * @return: N/A */ template<typename RandomIt, typename T = typename std::iterator_traits<RandomIt>::value_type> void sortBy(RandomIt first, RandomIt last, const std::vector<typename std::common_type<std::function<bool(T, T)>>::type>& conditions) { std::sort(first, last, [&](const T& lhs, const T& rhs) { return evaluate(conditions, lhs, rhs); }); } /** * FUNCTION: sortBy * USE: Sorts a sequence in ascending or descending order depending on the sorting condition * @param first: The first position of the sequence to be sorted * @param last: The last position of the sequence to be sorted * @param condition: A comparison function by which the sequence should be sorted * @return: N/A */ template<typename RandomIt, typename T = typename std::iterator_traits<RandomIt>::value_type> void sortBy(RandomIt first, RandomIt last, const typename std::common_type<std::function<bool(T, T)>>::type& condition) { std::vector<std::function<bool(T, T)>> conditions = { condition }; sortBy(first, last, conditions); } /** * FUNCTION: sortBy * USE: Sorts a sequence in ascending order * @param first: The first position of the sequence to be sorted * @param last: The last position of the sequence to be sorted * @return: N/A */ template<typename RandomIt, typename T = typename std::iterator_traits<RandomIt>::value_type> void sortBy(RandomIt first, RandomIt last) { auto condition = [](const T& lhs, const T& rhs) { return lhs < rhs; }; sortBy(first, last, condition); } }// http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 |
// ============================================================================ // Author: Kenneth Perkins // Date: Mar 8, 2021 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include <vector> #include <utility> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare array int arry[] = { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; // Get array size int size = sizeof(arry) / sizeof(arry[0]); // Sort array in default ascending order Utils::sortBy(arry, arry + size); // Display results for (int index = 0; index < size; ++index) { std::cout << arry[index] << std::endl; } display(""); // Declare sort condition auto condition = [](const auto& lhs, const auto& rhs) { return lhs > rhs; }; // Sort array in descending order Utils::sortBy(arry, arry + size, condition); // Display results for (int index = 0; index < size; ++index) { std::cout << arry[index] << std::endl; } display(""); // Declare object struct Person { int id; std::string name; }; // Declare data std::vector<Person> people = { {31, "Kenneth"}, {28, "Jennifer"}, {87, "Lynn"}, {91, "Sole"}, {22, "Kenneth"}, {19, "Jennifer"} }; // Sort vector by name length ASC, id DESC Utils::sortBy(people.begin(), people.end(), { [](const auto& lhs, const auto& rhs) { return lhs.name.length() < rhs.name.length(); }, [](const auto& lhs, const auto& rhs) { return lhs.id > rhs.id; } }); // Display results for (const auto& person : people) { std::cout << person.id << " - " << person.name << std::endl; } display(""); struct Student { std::string name; // Given int math; // Marks in math (Given) int phy; // Marks in Physics (Given) int che; // Marks in Chemistry (Given) int total; // Total marks (To be filled) int rank; // Rank of student (To be filled) }; const int n = 5; // array of structure objects Student a[n]; // Details of Student 1 a[0].name = "Bryan"; a[0].math = 80; a[0].phy = 95; a[0].che = 85; // Details of Student 2 a[1].name = "Kevin"; a[1].math = 95; a[1].phy = 85; a[1].che = 99; // Details of Student 3 a[2].name = "Nicky"; a[2].math = 95; a[2].phy = 85; a[2].che = 80; // Details of Student 4 a[3].name = "Steve"; a[3].math = 80; a[3].phy = 70; a[3].che = 90; // Details of Student 5 a[4].name = "Rohan"; a[4].math = 80; a[4].phy = 80; a[4].che = 80; for (int i = 0; i < n; i++) a[i].total = a[i].math + a[i].phy + a[i].che; Utils::sortBy(a, a + n, { [](const auto& lhs, const auto& rhs) { return lhs.math > rhs.math; }, [](const auto& lhs, const auto& rhs) { return lhs.phy > rhs.phy; }, [](const auto& lhs, const auto& rhs) { return lhs.che > rhs.che; } }); for (int i = 0; i < n; i++) a[i].rank = i + 1; // Column names for displaying data std::cout << "Rank" << " " << "Name" << " "; std::cout << "Maths" << " " << "Physics" << " " << "Chemistry"; std::cout << " " << "Total\n"; // Display details of Students for (int i = 0; i < n; i++) { std::cout << a[i].rank << " "; std::cout << a[i].name << " "; std::cout << a[i].math << " " << a[i].phy << " " << a[i].che << " "; std::cout << a[i].total << " "; std::cout << "\n"; } using my_pair = std::pair<double, double>; std::vector<my_pair> data; data.push_back(my_pair(3, 2)); data.push_back(my_pair(1, 2)); data.push_back(my_pair(1, 1)); data.push_back(my_pair(2, 2)); Utils::sortBy(data.begin(), data.end(), { [](const auto& lhs, const auto& rhs) { return lhs.first < rhs.first; }, [](const auto& lhs, const auto& rhs) { return lhs.second > rhs.second; } }); display(""); for (const auto& p : data) { std::cout << p.first << ' ' << p.second << std::endl; } display(""); struct Node { int x; int y; float value; }; std::vector<Node> vec{ {5, 6, 0.f}, {2, 4, 0.f}, {1, 1, 0.f}, {1, 0, 0.f}, {8, 10, 0.f}, {4, 7, 0.f}, {7, 1, 0.f}, {5, 4, 0.f}, {6, 1, 0.f}, {1, 4, 0.f}, {3, 10, 0.f}, {7, 2, 0.f} }; Utils::sortBy(vec.begin(), vec.end(), { [](const Node& lhs, const Node& rhs) { return lhs.y < rhs.y; }, [](const Node& lhs, const Node& rhs) { return lhs.x < rhs.x; } }); std::cout << "x y" << std::endl << std::endl; for (const auto& item : vec) { std::cout << item.x << " " << item.y << std::endl; } } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// 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.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
// ============================================================================ // 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 1987The 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
#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/ |
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 81The 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.5The 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 NotesThe 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 11, 2012 // Taken From: http://programmingnotes.org/ // File: bubbleSort.cpp // Description: Demonstrates how to sort an array using bubble sort // ============================================================================ #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; cin.get(); 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:
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 ======
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 11, 2012 // Taken From: http://programmingnotes.org/ // File: selectionSort.cpp // Description: Demonstrates how to sort an array using selection sort // ============================================================================ #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; cin.get(); 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 < arraySize; ++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:
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 ======
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 11, 2012 // Taken From: http://programmingnotes.org/ // File: insertionSort.cpp // Description: Demonstrates how to sort an array using insertion sort // ============================================================================ #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; cin.get(); return 0; }// end of main void InsertionSort(int arry[], int arraySize) { int previousIndex = 0; int currentValue = 0; // iterate through entire list for (int index = 1; index < arraySize; ++index) { currentValue = arry[index]; previousIndex = index - 1; while (previousIndex >= 0 && arry[previousIndex] > currentValue) { arry[previousIndex + 1] = arry[previousIndex]; previousIndex = previousIndex - 1; }// end while loop arry[previousIndex + 1] = currentValue; }// end for loop }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 11, 2012 // Taken From: http://programmingnotes.org/ // File: quickSort.cpp // Description: Demonstrates how to sort an array using quick sort // ============================================================================ #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); void QuickSort(int arry[], int start, int end); int Partition(int arry[], int start, int end); 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; cin.get(); return 0; }// end of main // the initial function call and initiates the sort void QuickSort(int arry[], int arraySize) { QuickSort(arry, 0, arraySize - 1); }// end of QuickSort // recursive call that carries out the sort void QuickSort(int arry[], int start, int end) { if (start < end) { // partition the arry and get the new pivot position int newPiviotIndex = Partition(arry, start, end); // quick sort the first part QuickSort(arry, start, newPiviotIndex); // quick sort the second part QuickSort(arry, newPiviotIndex + 1, end); } }// end of QuickSort int Partition(int arry[], int start, int end) { // choose a random pivot int pivotIndex = start + rand() % (end - start + 1); std::swap(arry[end], arry[pivotIndex]); // swap pivot with last element int left = start; // left index int right = end; // right index // compare and select smallest from the subarray for (int index = start; index <= right; ++index) { if (arry[index] < arry[right]) { std::swap(arry[index], arry[left]); ++left; } } // move pivot to its final place std::swap(arry[right], arry[left]); return left; // return the position of the new pivot }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 11, 2012 // Taken From: http://programmingnotes.org/ // File: mergeSort.cpp // Description: Demonstrates how to sort an array using merge sort // ============================================================================ #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 arraySize); void MergeSort(int arry[], int start, int end); void Merge(int arry[], int start, int midPt, int end); 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, NUM_INTS); 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; cin.get(); return 0; }// end of main // the initial function call and initiates the sort void MergeSort(int arry[], int arraySize) { MergeSort(arry, 0, arraySize - 1); }// end of MergeSort // recursive call that carries out the sort 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, end); } }// end of MergeSort // sorts the sub array void Merge(int arry[], int start, int midPt, int end) { int leftFirst = start; int leftLast = midPt; int rightFirst = midPt + 1; int rightLast = end; int* tempArray = new int[rightLast + 1]; 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]; } delete[] tempArray; }// http://programmingnotes.org/ |
SAMPLE OUTPUT:
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
// ============================================================================ // Author: Kenneth Perkins // Date: Feb 7, 2012 // Taken From: http://programmingnotes.org/ // File: bubbleSort.cpp // Description: 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---------------------------------------------------------------\n\n"; 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 << "\n\n"; 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; } } // If no swaps were made in the last pass, // no need to continue the loop. Sorting complete. if (currentSwaps == 0) { break; } 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 << "\n\n"; // Keeps track of the amount of swaps and passes totalSwaps += currentSwaps; ++totalPasses; }// 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 95Array after bubble sort pass #2
0 1 2 3 4 6 10 4 15 17 35 95Array after bubble sort pass #3
0 1 2 3 4 6 4 10 15 17 35 95Array after bubble sort pass #4
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: 4