Question

This is a c++ code /**    Write a function sort that sorts the elements of...

This is a c++ code

/**   
Write a function sort that sorts the elements of a std::list
without using std::list::sort or std::vector.
Instead use list<int>::iterator(s)
*/
using namespace std;
#include <iostream>
#include <iomanip>
#include <string>
#include <list>
void print_forward (list<int>& l)
{
// Print forward
for (auto value : l)
{
cout << value << ' ';
}
cout << endl;
}
void sort(list<int>& l)
{

write code here -- do not use the built-in list sort function

}
int main ()
{
list<int> l { 2, 24, 3, -4, 32, -22};
print_forward(l);
sort(l);
print_forward(l);
return 0;
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hey, it's a very good exercise of using iterators and sorting without using any extra libraries.

For understanding purpose, I had divided the solution into parts. So, let's start:

PART ONE: REQUIREMENTS:

The major challenge is that we need to sort the list but without using the standard sort of List or Vector. Now, we have to use a list iterator and we need to sort using that only.

PART TWO: WRITING SORT() METHOD:

1. Writing out sort() Method:

Taking a variable to check whether a list is sorted or not. Considering initially the list will be not sorted and hence initializing to false.

2. If not sorted, perform operations to sort it and check whether the list is sorted or not.

Take two lists <int> iterators for accessing the elements of the list.

The iterator front will access the first and front_advanced will access the character next to it.

3. Applying Bubble sort logic:

We have implemented bubble sort logic and updated the variable isSorted. When the swappings are not required, it means the list is sorted and the operation will complete.

4. Full Code:

PART THREE: FULL CODE IMPLEMENTATION IN CODE FORMAT:

*****************************CODE*************************

 void sort(list<int>& l) {       //A Variable to check whether list is sorted or not.    bool isSorted = false; while (!isSorted) {      isSorted = true;        //Iterator for accessing elements of list       list <int>::iterator front;       list <int>::iterator front_advanced;              //Applying Basic Sorting algorithm on these iterators   for (front = l.begin(), front_advanced = front++; front_advanced != l.end(); ++front_advanced, ++front)         {        //Checking each element with the element next to it            if ((*front_advanced) > (*front)) { //This means List is not sorted and swapping will take place. isSorted = false; std::iter_swap(front_advanced, front); }         }        } }

*************************************************CODE*******************************************

========================================================================

void sort(list<int>& l)
{
   //A Variable to check whether list is sorted or not.
   bool isSorted = false;
while (!isSorted)
{
   isSorted = true;

   //Iterator for accessing elements of list
   list <int>::iterator front;
   list <int>::iterator front_advanced;
  
   //Applying Basic Sorting algorithm on these iterators
   for (front = l.begin(), front_advanced = front++; front_advanced != l.end(); ++front_advanced, ++front)  
   {
   //Checking each element with the element next to it
       if ((*front_advanced) > (*front))
{
//This means List is not sorted and swapping will take place.
isSorted = false;
  
std::iter_swap(front_advanced, front);
  
}
  
   }
  
}
}

========================================================================

Thanks and All the best.

Happy Coding

Please don't forget to thumbs up if it really helped you.

Keep learning and Keep Chegging :)

Add a comment
Know the answer?
Add Answer to:
This is a c++ code /**    Write a function sort that sorts the elements of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • C++, data structure Write a solution to test 2 problem 3 that uses selection sort to sort the ite...

    c++, data structure Write a solution to test 2 problem 3 that uses selection sort to sort the items in the vector of integers. #include <iostream> #include <iterator> #include <string> #include <random> using namespace std; void insertionSort(int a[], int N) {    int sorted = 0;    for (int sorted = 0; sorted < N - 1; ++sorted)    {        int item_position = sorted + 1;        int item = a[item_position];        while (item_position > 0 && a[item_position - 1] > item)        {            a[item_position] =...

  • Write a c++ code into the given code  to find composite numbers from the given random number...

    Write a c++ code into the given code  to find composite numbers from the given random number list. The composite numbers is only counted once if there is a repeated number. I need to use this code and add on a code to find if the numbers generated is a composite function. Please help #include <cmath> #include <cstdlib> #include <ctime> #include <iostream> #include <vector> using namespace std; int main() {    srand(time(NULL)); int size_of_list = 0; // the number of random...

  • a) Hand-trace the following program and determine and write down what is the output of the...

    a) Hand-trace the following program and determine and write down what is the output of the code.                b) Run the code and compare the program output to your hand-traced result obtained from part (a). #include <iostream> #include <iomanip> using namespace std; void f(); int x = 5; int main() {         cout << "x = " << x << endl;         int x = 6;         cout << "x = " << x << endl;         {                int...

  • Objective: 1. Understand sorting algorithm 2. Implement bubble sort in C++ Check slides for a template...

    Objective: 1. Understand sorting algorithm 2. Implement bubble sort in C++ Check slides for a template of the solution, if you need Write a program that asks users to input 10 integers into an array, write a function that takes the array as its argument, use bubble sort to sort the array and output the sorted array in increasing order. #include <iostream> using namespace std; C:IWINDOWSSystems2cmd.exe lease input 10 integers: void bubblesort(int a[10]) int help; int b[10]; for (int i...

  • C++ Write a function so that the main() code below can be replaced by the simpler...

    C++ Write a function so that the main() code below can be replaced by the simpler code that calls function MphAndMinutesToMiles(). Original main(): int main() { double milesPerHour; double minutesTraveled; double hoursTraveled; double milesTraveled; cin >> milesPerHour; cin >> minutesTraveled; hoursTraveled = minutesTraveled / 60.0; milesTraveled = hoursTraveled * milesPerHour; cout << "Miles: " << milesTraveled << endl; return 0; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <iostream> using...

  • //CODE 16-02.cpp //Demonstrates a template function that implements //a generic version of the selection sort algorithm....

    //CODE 16-02.cpp //Demonstrates a template function that implements //a generic version of the selection sort algorithm. #include <iostream> using std::cout; using std::endl; template<class T> void sort(T a[], int numberUsed); //Precondition: numberUsed <= declared size of the array a. //The array elements a[0] through a[numberUsed - 1] have values. //The assignment and < operator work for values of type T. //Postcondition: The values of a[0] through a[numberUsed - 1] have //been rearranged so that a[0] <= a[1] <=... <= a[numberUsed -...

  • The following C++ code include 3 files: Patient.h, Patient.cpp and Main.cpp. The program basically creates and stores patient records. The original code has everything in a single .cpp file. I tried t...

    The following C++ code include 3 files: Patient.h, Patient.cpp and Main.cpp. The program basically creates and stores patient records. The original code has everything in a single .cpp file. I tried to divide the code in 3 parts (Patient.h, Patient.cpp and Main.cpp), but it is giving me errors. Patient.h #ifndef PATIENT_H #define PATIENT_H #include <string> #include "Patient.cpp" using namespace std; class Patient{ private : string firstname; string lastname; string location; static int cnt; int id; public : Patient(string, string, string);...

  • Change the the following C++ codes to list the "marks" reported Alphabetically. --------------------------------------------------------------------------------------------------------- #include <iostream> #include<string.h>...

    Change the the following C++ codes to list the "marks" reported Alphabetically. --------------------------------------------------------------------------------------------------------- #include <iostream> #include<string.h> using namespace std; void display(int marks[10]); int main() { int marks[10]; int i;x for (i=0; i<10; i++) { cout << "Enter marks : "; cin >> marks[i]; } display(marks); return 0; } // Create the function sort to sort the marks in alphabetical order void display(int marks[10]) { cout <<"Displaying marks in Ascending Order " << endl; for (int i = 0; i <10;...

  • (c++) Write a predicate function that checks whether two vectors have the same elements in the...

    (c++) Write a predicate function that checks whether two vectors have the same elements in the same order. Write a predicate function that checks whether two vectors have the same elements in the same order bool equals(vector<int> a, vector<int> b) provided code : #include <iostream> #include <vector> using namespace std; bool equals(vector<int> a, vector<int> b) { // TODO } int main() { // TODO // Print Expected, "Vectors a and b are " (print "equal." if they are. Otherwise, print...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT