In: Computer Science
Write a program in C++ to test either the selection sort or insertion sort algorithm for array-based lists as given in the chapter.
Test the program with at least three (3) lists.
Supply the program source code and the test input and output.
List1: 14,11,78,59
List2: 15, 22, 4, 74
List3: 14,2,5,44
#include <iostream>
using namespace std;
void insertionsort(int values[],int numValues)
{
int n = numValues;
for (int i=1; i<n; ++i)
{
int key = values[i];
int j = i-1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j>=0 && values[j] > key)
{
values[j+1] = values[j];
j = j-1;
}
values[j+1] = key;
}
}
void printArray(int arr[],int n){
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<endl;
}
int main()
{
int arr1[]={14,11,78,59};
cout<<"Before Sort: \n";
printArray(arr1,4);
insertionsort(arr1,4);
cout<<"After Sort: \n";
printArray(arr1,4);
int arr2[]={15, 22, 4, 74};
cout<<"Before Sort: \n";
printArray(arr2,4);
insertionsort(arr2,4);
cout<<"After Sort: \n";
printArray(arr2,4);
int arr3[]={14,2,5,44};
cout<<"Before Sort: \n";
printArray(arr3,4);
insertionsort(arr3,4);
cout<<"After Sort: \n";
printArray(arr3,4);
return 0;
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me