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] =...

  • C++ Write a recursive function that reverses the given input string. No loops allowed, only use...

    C++ Write a recursive function that reverses the given input string. No loops allowed, only use recursive functions. Do not add more or change the parameters to the original function. Do not change the main program. #include <iostream> #include <string> using namespace std; //Write a recursive function 'void reverse(string &str)' that reverses the given input string. void reverse(string &str) { /*Code needed*/ } int main() {    string name = "sherry";    reverse(name);    cout << name << endl; //should...

  • 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...

  • I need to add something to this C++ program.Additionally I want it to remove 10 words...

    I need to add something to this C++ program.Additionally I want it to remove 10 words from the printing list (Ancient,Europe,Asia,America,North,South,West ,East,Arctica,Greenland) #include <iostream> #include <map> #include <string> #include <cctype> #include <fstream> #include <iomanip> using namespace std; void addWord(map<std::string,int> &words,string s); void readFile(string infile,map<std::string,int> &words); void display(map<std::string,int> words);    int main() { // Declaring variables std::map<std::string,int> words;       //defines an input stream for the data file ifstream dataIn;    string infile; cout<<"Please enter a File Name :"; cin>>infile; readFile(infile,words);...

  • 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...

  • 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);...

  • 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...

  • C++ problem. hi heys, i am trying to remove beginning and the end whitespace in one...

    C++ problem. hi heys, i am trying to remove beginning and the end whitespace in one file, and output the result to another file. But i am confused about how to remove whitespace. i need to make a function to do it. It should use string, anyone can help me ? here is my code. #include <iostream> #include <iomanip> #include <cstdlib> #include <fstream> using namespace std; void IsFileName(string filename); int main(int argc, char const *argv[]) { string inputfileName = argv[1];...

  • I need to make a few changes to this C++ program,first of all it should read...

    I need to make a few changes to this C++ program,first of all it should read the file from the computer without asking the user for the name of it.The name of the file is MichaelJordan.dat, second of all it should print ,3 highest frequencies are: 3 words that occure the most.everything else is good. #include <iostream> #include <map> #include <string> #include <cctype> #include <fstream> #include <iomanip> using namespace std; void addWord(map<std::string,int> &words,string s); void readFile(string infile,map<std::string,int> &words); void display(map<std::string,int>...

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