Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //DISPLAY 7.12 Sorting an Array
- //Tests the procedure sort.
- #include <iostream>
- #include <vector>
- #include <string>
- using namespace std;
- void fill_array(vector<string> &a);
- //Precondition: size is the declared size of the array a.
- //Postcondition: number_used is the number of values stored in a.
- //a[0] through a[number_used - 1] have been filled with
- //nonnegative integers read from the keyboard.
- void sort(vector<string> &a);
- //Precondition: number_used <= declared size of the array a.
- //The array elements a[0] through a[number_used - 1] have values.
- //Postcondition: The values of a[0] through a[number_used - 1] have
- //been rearranged so that a[0] <= a[1] <= ... <= a[number_used - 1].
- void swap_values(string& v1, string& v2);
- //Interchanges the values of v1 and v2.
- int index_of_smallest(const vector<string> a, int start_index);
- //Precondition: 0 <= start_index < number_used. Referenced array elements have
- //values.
- //Returns the index i such that a[i] is the smallest of the values
- //a[start_index], a[start_index + 1], ..., a[number_used - 1].
- int main( )
- {
- cout << "This program sorts numbers from lowest to highest.\n";
- vector<string> sample_array;
- fill_array(sample_array);
- sort(sample_array);
- cout << "In sorted order the numbers are:\n";
- for (int index = 0; index < sample_array.size(); index++)
- cout << sample_array[index] << " ";
- cout << endl;
- return 0;
- }
- //Uses iostream:
- void fill_array(vector<string> a)
- {
- string q = "3";
- a.pushback(q);
- string w = "2";
- a.pushback(w);
- string e = "1";
- a.pushback(e);
- }
- void sort(vector<string>a)
- {
- int index_of_next_smallest;
- //<The rest of the definition of fill_array is given in Display 7.9.>
- for (int index = 0; index < a.size() - 1; index++)
- {//Place the correct value in a[index]:
- index_of_next_smallest =
- index_of_smallest(a, index);
- swap_values(a[index], a[index_of_next_smallest]);
- //a[0] <= a[1] <=...<= a[index] are the smallest of the original array
- //elements. The rest of the elements are in the remaining positions.
- }
- }
- void swap_values(string& v1, string& v2)
- {
- string temp;
- temp = v1;
- v1 = v2;
- v2 = temp;
- }
- int index_of_smallest(const int a[], int start_index, int number_used)
- {
- int min = a[start_index],
- index_of_min = start_index;
- for (int index = start_index + 1; index < number_used; index++)
- if (a[index] < min)
- {
- min = a[index];
- index_of_min = index;
- //min is the smallest of a[start_index] through a[index]
- }
- return index_of_min;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement