Start New Discussion within our Software Development Community

Hi there people!

I am trying to implement various sort methods in one program, just to practise implementing sort methods for one of my courses at varsity.

However, my method works fine, the moment I use the pointer that it returned, it broke. Here is my program:

#include <iostream>
#include <cstdio>

using namespace std;

template <class T>
T* insertionSort(T arr[], int size);
template <class T>
void printArray(T* p, int size);

int main()
{
	int size=7;
	int arr[7]={100, 15, 8, 65, 250, 16, 75};
	int* p=arr;
	p=insertionSort(arr, size);

	printArray(p, size);
}

template <class T>
T* insertionSort(T arr[], int size)
{
	T data[size];
	T* ptr=data;
	for (int i=0; i<size; i++)
	{
		*ptr=arr[i];
		ptr++;
	}
	ptr=data;
	printArray(ptr, size);

	for (int i=1,j=0; i<size; i++)
	{
		T tmp=data[i];
		for (j=i; j>0 && tmp<data[j-1]; j--)
			data[j]=data[j-1];
		data[j]=tmp;
	}
	ptr=data;
	printArray(ptr, size);
	return ptr;
}

template <class T>
void printArray(T* p, int size)
{
	for (int i=0; i<size; i++)
	{
		cout<<*p<<" ";
		p++;
	}
	cout<<endl;
}

<< moderator edit: added code tags: [co[u][/u]de][/co[u][/u]de] >>

Here is my output:

Before sorting data = 100 15 8 65 250 16 75
After sorting data = 8 15 16 65 75 100 250

pointer in main program's value = 8 7 -1073745776 -1073745596 -1073745736 134514975 134520184


Please help, I am stumped...

This article has been dead for over six months. Start a new discussion instead.