Could you please convert this to C++ it\'s an InsertionSort import java.util.Sca
ID: 3661627 • Letter: C
Question
Could you please convert this to C++ it's an InsertionSort
import java.util.Scanner;
public class InsertionSort
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int[] numbers = new int[10];
//Please note that arrays in C++ are not objects
System.out.println("Please input " + numbers.length + " numbers ");
//Populate array from user
for(int i=0; i < numbers.length; i++)
{
numbers[i] = input.nextInt();
}
//print array before sort
System.out.print("Numbers before sort:");
for(int i=0; i < numbers.length; i++)
{
System.out.print(" " + numbers[i]);
}
System.out.println();
//Sort the array
for(int i=1; i < numbers.length; i++)
{
int temp = numbers[i];
int j = i-1;
while(j >= 0 && numbers[j] > temp)
{
numbers[j+1] = numbers[j];
j--;
}
numbers[j+1] = temp;
}
//print array after sort
System.out.print("Numbers after sort:");
for(int i=0; i < numbers.length; i++)
{
System.out.print(" " + numbers[i]);
}
System.out.println();
}
}
Explanation / Answer
#include<iostream>
using namespace std;
void INSERTION_SORT(int [],int );
int main()
{
char ch;
do
{
int n;
cout<<"Enter the no. of elements in the array"<<endl;
cin>>n;
int a[n];
cout<<"Enter the elements in the array"<<endl;
for(int i=1;i<=n;i++)
{
cin>>a[i];
}
INSERTION_SORT(a,n);
cout<<"::::Sorted Output:::"<<endl;
for(int k=1;k<=n;k++)
{
cout<<a[k]<<" ";
}
cout<<endl<<
"Press 'y' or 'Y' to continue!!!";
cin>>ch;
}while(ch=='y'||ch=='Y');
return 0;
}
void INSERTION_SORT(int a[],int n)
{
int key,i,j;
for(j=2;j<=n;j++)
{
key=a[j];
i=j-1;
while((i>0)&&(a[i]>key))
{
a[i+1]=a[i];
i=i-1;
}
a[i+1]=key;
}
}