Insertion Sort

Hi, this is a program to sort an array using nsertion sort but an infinite loop is created i dont know how. Please help

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using namespace std;
#include<iostream>
void Insertsort(int Arr[],int N);
int main()
{
	int A[50],i,size;
	cout<<"Enter size of array ";
	cin>>size;
	cout<<"Enter elements of array ";
	for(i=0;i<size;i++)
	cin>>A[i];
	
	Insertsort(A,size);
	cout<<endl;
	cout<<"The sorted array is "<<endl;
	for(i=0;i<size;i++)
	cout<<A[i]<<" ";
}

void Insertsort(int Arr[],int N)
{
	int i,j,k,hold;
	for(i=1;i<N;i++)
	{
		i=j;
		while(Arr[i]<Arr[j-1])
		{
			hold=Arr[j-1];
			Arr[j-1]=Arr[i];
			Arr[i]=hold;
			j--;
		}
	
		cout<<"Array after round "<<i+1<<": ";
		for(k=0;k<N;k++)
		cout<<Arr[k]<<" ";
		cout<<endl;
	}
}
Two problems.

in main(), the program needs to maintain the size of the array. So an allocation of 50 spaces are available, but if you only enter 2 values, the size should be 2. It is this 2 that should be passed to Insertsort().

I Insertsort(), once you have found the insertion point (with the for loop), you should insert the value moving the remaining values down (as you do with the while loop), then insert the item, then return. There's no need to keep going around the outer for loop.
Topic archived. No new replies allowed.