R
ritchie
Hi,
I am writing to ask if anyone can see why my array is not being sorted
correctly?
It's an array of 4 elements(ints 1,2,3,4) but after calling the
selection sort
it comes back sorted as 1,1,2,4.
I have narrowed it down to the sort function. I'm almost positive
that the error lies within sort?
I have included the full program.
Any ideas?
Thanks in advance,
Ritchie.
*******************start code****************************
#include<stdio.h>
#define MAX 4
void sort(int [], int ); //sort function
main()
{
int iArr[MAX] = {1,2,3,4}; //original array
int iTmpArr[MAX]; // tmp array...for copying
// int iMenuChoice = 0;
int i;
//copy iArr to iTmpArr
for(i=0;i<MAX;i++)
{
iTmpArr = iArr;
}
sort(iTmpArr, MAX); //call selection sort
}
void sort( int iTmpArr[], int iMax)
{
int i, iSmallestElement, iSortElement, iTemp;
printf("\n****************Selection Sort****************\n");
for( iSortElement=0; iSortElement <iMax-1; iSortElement++ )
{
iSmallestElement = iSortElement;
for( i=iSortElement +1; i <= iMax; i++ )
{
if( iTmpArr[ i ] < iTmpArr[ iSmallestElement ] )
iSmallestElement = i;
if( iSmallestElement != iSortElement )
{
iTemp = iTmpArr[ iSmallestElement ];
iTmpArr[ iSmallestElement ] = iTmpArr[ iSortElement ];
iTmpArr[ iSortElement ] = iTemp;
}
}
}
printf("Sorted array\n");
for(i=0; i<iMax;i++)
printf("%d ", iTmpArr);
printf("\n");
}
***********************end of code*************************
I am writing to ask if anyone can see why my array is not being sorted
correctly?
It's an array of 4 elements(ints 1,2,3,4) but after calling the
selection sort
it comes back sorted as 1,1,2,4.
I have narrowed it down to the sort function. I'm almost positive
that the error lies within sort?
I have included the full program.
Any ideas?
Thanks in advance,
Ritchie.
*******************start code****************************
#include<stdio.h>
#define MAX 4
void sort(int [], int ); //sort function
main()
{
int iArr[MAX] = {1,2,3,4}; //original array
int iTmpArr[MAX]; // tmp array...for copying
// int iMenuChoice = 0;
int i;
//copy iArr to iTmpArr
for(i=0;i<MAX;i++)
{
iTmpArr = iArr;
}
sort(iTmpArr, MAX); //call selection sort
}
void sort( int iTmpArr[], int iMax)
{
int i, iSmallestElement, iSortElement, iTemp;
printf("\n****************Selection Sort****************\n");
for( iSortElement=0; iSortElement <iMax-1; iSortElement++ )
{
iSmallestElement = iSortElement;
for( i=iSortElement +1; i <= iMax; i++ )
{
if( iTmpArr[ i ] < iTmpArr[ iSmallestElement ] )
iSmallestElement = i;
if( iSmallestElement != iSortElement )
{
iTemp = iTmpArr[ iSmallestElement ];
iTmpArr[ iSmallestElement ] = iTmpArr[ iSortElement ];
iTmpArr[ iSortElement ] = iTemp;
}
}
}
printf("Sorted array\n");
for(i=0; i<iMax;i++)
printf("%d ", iTmpArr);
printf("\n");
}
***********************end of code*************************