C++ Homework help Hello, I need help in making an insertionsort method similar t
ID: 3562933 • Letter: C
Question
C++ Homework help
Hello, I need help in making an insertionsort method similar to this excahnge sort method: -
void SortingMachine1::exchangeSort (ListOfT& s)
{
T x;
for (int i = 0, z = s.rightLength(); i < z; i++) {
s.removeRightFront(x);
for (int k = 0; k < (z - 1); k++) {
if (TCompare::areOrdered(x, s.rightFront())) {
s.replaceRightFront(x);
} // end if
s.advance();
} // end for
s.addRightFront(x);
s.moveToStart();
} // end for
} // exchangeSort
Insertion sort decleration is this: -
void insertionSort (alters ListOfT& s, consumes T& x);
// requires: s.left = < > and Sorted(s.right)
// ensures: s.left = < > and
// there exists sPre, sPost: String(T),
// #s.right = sPre * sPost and
// s.right = sPre * * sPost and
// Sorted(s.right) and
// perms(#s.right, sPre * sPost)
IMPORTANT: THIS NEEDS TO BE RECURSIVE
The tempelate needed is here: - http://pastebin.com/ptgwAfeV
Explanation / Answer
#include <cstdlib>
#include <iostream>
using namespace std;
//member function
void insertion_sort(int arr[], int length);
void print_array(int array[],int size);
int main() {
int array[5]= {5,4,3,2,1};
insertion_sort(array,5);
return 0;
}//end of main
void insertion_sort(int arr[], int length) {
int i, j ,tmp;
for (i = 1; i < length; i++) {
j = i;
while (j > 0 && arr[j - 1] > arr[j]) {
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
j--;
}//end of while loop
print_array(arr,5);
}//end of for loop
}//end of insertion_sort.
void print_array(int array[], int size){
cout<< "sorting: ";
int j;
for (j=0; j<size;j++)
for (j=0; j<size;j++)
cout <<" "<< array[j];
cout << endl;
}//end of print_array
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.