-
Whats wrong with this?
Code:
// This is the main project file for VC++ application project
// generated using an Application Wizard.
#include "stdafx.h"
#using <mscorlib.dll>
using namespace System;
void printA(Int32 []); //Passing Array To a Funciton
void populate(Int32[],int,int);
void split(Int32 [],Int32 [],Int32 []);
int _tmain()
{
int n;
Console::Write(S"How Many Elements wou you like? ");
n=Int32::Parse(Console::ReadLine());
Int32 y[]= new Int32[n];
Int32 x[]= new Int32[n/2];
Int32 z[]= new Int32[n/2];
int a =1, b=11;
populate(y,a,b);
printA(y);
split(y,x,z);
return 0;
}
void printA(Int32 b[]){
for(int i=0; i<b->Length; i++)
Console::WriteLine(S"{0}",
b[i].ToString());
}
void populate(Int32 a[], int low, int high) {
Random *r;
r= new Random();
for(int i=0; i<a->Length; i++)
a[i] =r->Next(low,high);
}
void split(Int32 a[], Int32 a1[], Int32 a2[]) {
int mid = (a->Length)/2;
for (int i=0; i!=mid; i++){
a1[i]=a[i];
for(int j =mid; j!=a->Length; j++)
a2[i]= a[j];
}
Console::WriteLine(S"SubArray1: ");
printA(a1);
Console::WriteLine(S"SubArray2: ");
printA(a2);
}
I am trying to split an array in half and store each halve in a separate subarray. The first subarray outputs fine, the second subarray skips the element a[n-1] and instead outputs a[n] twice. Its probably a simple fix that I am not seeing right now. Thanks for the help.
-
> Int32 z[]= new Int32[n/2];
This should probably be:
Int32 z[]= new Int32[n/2+1];
Because if your original array is 9 elements, your second subarray will contain 5 elements.
Code:
> for (int i=0; i!=mid; i++){
> a1[i]=a[i];
> for(int j =mid; j!=a->Length; j++)
> a2[i]= a[j];
> }
I think you want two separate for-loops:
Code:
for (int i=0; i!=mid; i++){
a1[i]=a[i];
}
for(int i=0,int j =mid; j!=a->Length; i++,j++){
a2[i]= a[j];
}
-
NVM I found my own mistake. For those that would like to know what was wrong here is the modified split function:
Code:
void split(Int32 a[], Int32 a1[], Int32 a2[]) {
int mid = (a->Length)/2;
for (int i=0; i!=mid; i++)
a1[i]=a[i];
for( int j = 0 ; (j+mid)!=a->Length; j++)
a2[j]= a[j+mid];
Console::WriteLine(S"SubArray1: ");
printA(a1);
Console::WriteLine(S"SubArray2: ");
printA(a2);
}
I had one for loop inside the other which was wrong.
-
hehe u beatme to it swoopy. Yeah I made it so that it only does an even array because I am ultimately trying to code the merge sort algorithm.
-
>hehe u beatme to it swoopy.
By mere seconds. ;)