I am writing this partition code and there seems to be some problems with my RandomInRange function
Does anyone know how to write this Swap function? Ok,so I got the first few bugs fixed, the last problem is (I think) with my Swap() function.
#include <iostream>
#include <cstdio>
#include <stdlib.h>
#include <exception>
using namespace std;
int RandomInRange(int start,int end)
{
return (rand()%(end-start+1)+start);
}
void Swap(int* a,int* b)
{
int* temp=a;
a=b;
b=temp;
return;
}
int Partition(int data[],int length,int start,int end)
{
if(data==NULL || length<=0 || start<0 || end>=length)
{//throw new exception("Invalid Parameters.");
}
int index=RandomInRange(start,end);
Swap(&data[index],&data[end]);
int small = start-1;
for(index = start; index < end; ++index)
{
if(data[index]<data[end])
{
++small;
if(small!=index)
Swap(&data[index],&data[small]);
}
}
++small;
if(small != index)
Swap(&data[index],&data[small]);
return small;
}
int main(void)
{
int a[]={9,0,-4,23,5,21,3,-1};
Partition(a,8,1,8);
for(int i=0;i<8;i++)
cout<<a[i];
return 0;
}
//results={9,0,-4,23,5,21,3,-1}, so it's not actually sorted..
And emm,just a tiny question. Has anyone read the STL source code? Does it help to learn C++ and data structure? I was hoping to achive higher grades for my finals.
Also it says:
No matching constructor for initialization of 'std::exception'
when I try the code:
throw new exception("Invalid Parameters.");
That's why I commented that line.
In the below code
int Partition(int data[],int length,int start,int end)
{
if(data==NULL || length<=0 || start<0 || end>=length)
//throw new exception("Invalid Parameters.");
int index=RandomInRange(start,end);
Swap(&data[index],&data[end]);
after
if(data==NULL || length<=0 || start<0 || end>=length)
you have commented throwing the exception. Hence the program control moves to the next statement which calls the method RandomInRange()
whose arguments start and end are invalid. Hence this error.