Question

Implement Merge Sort and test it on a small list of 10 random integer values. c++...

Implement Merge Sort and test it on a small list of 10 random integer values. c++ please


template            // merge-sort S
void mergeSort(list& S, const C& less) {
typedef typename list::iterator Itor;       // sequence of elements
int n = S.size();
if (n <= 1) return;                   // already sorted
list S1, S2;
Itor p = S.begin();
for (int i = 0; i < n / 2; i++) S1.push_back(*p++);   // copy first half to S1
for (int i = n / 2; i < n; i++) S2.push_back(*p++);   // copy second half to S2
S.clear();                       // clear S's contents
mergeSort(S1, less);               // recur on first half
mergeSort(S2, less);               // recur on second half
merge(S1, S2, S, less);               // merge S1 and S2 into S
}


template
class Merge {                       // generic Merge
public:                        // global types
typedef std::list List;               // list type
void merge(List& A, List& B, List& C);       // generic merge function
protected:                        // local types
typedef typename List::iterator Itor;       // iterator type
// overridden functions
virtual void fromA(const E& a, List& C) = 0;
virtual void fromBoth(const E& a, const E& b, List& C) = 0;
virtual void fromB(const E& b, List& C) = 0;
};


template                // generic merge
void Merge::merge(List& A, List& B, List& C) {
Itor pa = A.begin();               // A's elements
Itor pb = B.begin();               // B's elements
while (pa != A.end() && pb != B.end()) {       // main merging loop
if (*pa < *pb)
fromA(*pa++, C);               // take from A
else if (*pa == *pb)
fromBoth(*pa++, *pb++, C);           // take from both
else
fromB(*pb++, C);               // take from B
}
while (pa != A.end()) { fromA(*pa++, C); }       // take rest from A
while (pb != B.end()) { fromB(*pb++, C); }       // take rest from B
}

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

#include <iostream>

void PrintArray(int *array, int n) {

  for (int i = 0; i < n; ++i)

    std::cout << array[i] << " " << std::flush;

  std::cout << std::endl;

}

void Merger(int arr[], int lo, int  mi, int hi){

    int *temp = new int[hi-lo+1];//temporary merger array

    int i = lo, j = mi + 1;//i is for left-hand,j is for right-hand

    int k = 0;//k is for the temporary array

    while(i <= mi && j <=hi){

        if(arr[i] <= arr[j])

            temp[k++] = arr[i++];

        else

            temp[k++] = arr[j++];

    }

    //rest elements of left-half

    while(i <= mi)

        temp[k++] = arr[i++];

    //rest elements of right-half

    while(j <= hi)

        temp[k++] = arr[j++];

    //copy the mergered temporary array to the original array

    for(k = 0, i = lo; i <= hi; ++i, ++k)

        arr[i] = temp[k];

    delete []temp;

}

void MergeSortHelper(int arr[], int lo, int hi){

    int mid;

    if(lo < hi){

        mid = (lo + hi) >> 1;

        MergeSortHelper(arr, lo, mid);

        MergeSortHelper(arr, mid+1, hi);

        Merger(arr, lo, mid, hi);

    }

}

void MergeSort(int arr[], int arr_size){

    MergeSortHelper(arr, 0, arr_size-1);

}

int main() {

  int array[] = {94, 42, 50, 95, 333, 65, 54, 456, 1, 1234};

  int n = sizeof(array)/sizeof(array[0]);

  std::cout << "Before Merge Sort :" << std::endl;

  PrintArray(array, n);

  MergeSort(array, n);

  std::cout << "After Merge Sort :" << std::endl;

  PrintArray(array, n);

  return (0);

}

/*

OUTPUT

Before Merge Sort :

94 42 50 95 333 65 54 456 1 2325

After Merge Sort :

1 42 50 54 65 94 95 333 456 2325

*/

Add a comment
Know the answer?
Add Answer to:
Implement Merge Sort and test it on a small list of 10 random integer values. c++...
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
  • In this assignment, you will implement a sort method on singly-linked and doubly-linked lists. Implement the...

    In this assignment, you will implement a sort method on singly-linked and doubly-linked lists. Implement the following sort member function on a singly-linked list: void sort(bool(*comp)(const T &, const T &) = defaultCompare); Implement the following sort member function on a doubly-linked list: void sort(bool(*comp)(const T &, const T &) = defaultCompare); The sort(…) methods take as a parameter a comparator function, having a default assignment of defaultCompare, a static function defined as follows: template <typename T> static bool defaultCompare(const...

  • 1. void raw_push_front(const Object &x) { // insert x at the head of the list *without*...

    1. void raw_push_front(const Object &x) { // insert x at the head of the list *without* using the iterator classes // Place your code here. } 2. void raw_push_back(const Object &x) { // insert x at the tail of the list *without* using the iterator classes // Place your code here. } #ifndef LIST_H #define LIST_H #include <algorithm> using namespace std; template<typename Object> class List { private: // The basic doubly linked list node. // Nested inside of List, can...

  • Language: C++ Complete this function 1.Object &raw_front() { // Return the element at the front of...

    Language: C++ Complete this function 1.Object &raw_front() { // Return the element at the front of the list *without* using the iterator classes // (You may assume the list is not empty) // Place your code here. Code: #ifndef LIST_H #define LIST_H #include using namespace std; template class List { private: // The basic doubly linked list node. // Nested inside of List, can be public // because the Node is itself private struct Node { Object data; Node *prev;...

  • in c++ please include all of the following " template class, template function, singly linked list,...

    in c++ please include all of the following " template class, template function, singly linked list, the ADT stack, copy constructor, operator overloading, "try catch"and pointers Modify the code named "Stack using a Singly Linked List" to make the ADT Stack that is a template class has the code of the destructor in which each node is directly deleted without using any member function. As each node is deleted, the destructor displays the address of the node that is being...

  • For this computer assignment, you are to write a C++ program to implement a class for...

    For this computer assignment, you are to write a C++ program to implement a class for binary trees. To deal with variety of data types, implement this class as a template. The definition of the class for a binary tree (as a template) is given as follows: template < class T > class binTree { public: binTree ( ); // default constructor unsigned height ( ) const; // returns height of tree virtual void insert ( const T& ); //...

  • Write a C++ program to validate computer user-ids and passwords. A list of valid ids and...

    Write a C++ program to validate computer user-ids and passwords. A list of valid ids and passwords (unsorted) is read from a file and stored in a Binary Search Tree (BST) of UserInfo objects. When user-ids and passwords are entered during execution, this BST is searched to determine whether they are legal. Input (file): UserInfo records for valid users Input (keyboard): Ids and passwords of users logging in Output (screen): Messages indicating whether user-ids and passwords are valid, as well...

  • Hello, I need to implement these small things in my C++ code. Thanks. 1- 10 characters...

    Hello, I need to implement these small things in my C++ code. Thanks. 1- 10 characters student first name, 10 characters middle name, 20 characters last name, 9 characters student ID, 3 characters age, in years (3 digits) 2- Open the input file. Check for successful open. If the open failed, display an error message and return with value 1. 3- Use a pointer array to manage all the created student variables.Assume that there will not be more than 99...

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
ADVERTISEMENT