Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- David Hawkins
- Data Structures & Algorithms
- SDEV-345-81
- 5/18/21
- Given the following set of data [23, 54, 2, 8, 3.2, 14, 43, 0, 9, 2] write an insertion sort algorithm
- to sort the listed data using an array. Using Big O, analyze your algorithm to show worst case
- running time. Make sure you show your work.
- */
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Header Files
- using namespace std;
- #include<iostream>
- #include<iomanip>
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Functions Prototypes
- void intro();
- void pad();
- void print(double*, int); // prints an array of doubles
- void isort(double*, int); // performs an insert sort with nested "for" loops
- void swap(double*, double*); // swaps the values of two doubles
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Main Function
- int main() {
- double test[10] = {23, 54, 2, 8, 3.2, 14, 43, 0, 9, 2};
- int size = sizeof(test) / sizeof(test[0]);
- //intro();
- cout << "The array that will be sorted by insert sort is: ";
- print(test, size);
- cout << endl;
- isort(test, size);
- cout << endl;
- cout << "The array after sorting is: ";
- print(test, size);
- return 0;
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Function Definitions
- void intro() {
- int x = 80;
- string pad;
- string intro = "This Is A Demonstartion Of Insert Sort";
- int cent = (80 - intro.length()) / 2;
- for (int i = 0; i < cent; i++)
- pad += ' ';
- cout << setw(x) << setfill('*') << '*' << endl;
- cout << setfill(' ') << right << pad << intro << endl;
- cout << setw(x) << setfill('*') << '*' << endl;
- }
- void pad() {
- cout << setw(80) << setfill('*') << '*' << endl;
- }
- void print(double* temp, int size) {
- cout << "{";
- for (int i = 0; i < size - 1; i++)
- cout << temp[i] << ", ";
- cout << temp[size - 1] << "}" << endl;
- return;
- }
- void isort(double* test, int size) {
- cout << "After 0 iterations: ";
- print(test, size);
- for (int i = 0; i < size-1; i++) {
- for (int j = i + 1; j < size; j++) {
- if (test[i] > test[j])
- swap(test[i], test[j]);
- }
- cout << "After " << i +1 << " iterations: ";
- print(test, size);
- }
- }
- void swap(double* x, double* y) {
- double temp = *x;
- *x = *y;
- *y = temp;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement