I wrote a quicksort program in C++.
- Is it okay to implement it this way?
- Am I using pointers correctly?
- Is my style okay?
- Any ideas to speed it up or save memory?
void change(int *i, int *j)
{
int temp = *j;
*j = *i;
*i = temp;
}
int *toplace(int *start, int *end)
{
int *i = start+1, *j= end;
while(i<=j)
{
for(; *i<=*start && i<=end; i++);
for(; *j>=*start && start+1<=j; j--);
if (i<j) change(i++,j--);
}
change(start,i-1);
return i-1;
}
void quicksort(int *start, int *end)
{
if (start >= end) return;
for(int *debug = start;debug<=end;debug++) std::cout<<*debug <<" ";
std::cout<<std::endl; //this and...
int *temp = start;
temp = toplace(start,end);
for(int *debug = start;debug<=end;debug++) std::cout<<*debug <<" ";
std::cout<<std::endl; //...this are only to "see under the hood"
std::cout<<std::endl;
quicksort(start,temp-1);
quicksort(temp+1,end);
}
An example usage:
int main(int argc, char* argv[])
{
int A[] = {5,14,8,12,1,2,11,15,6,9,7,3,13,4,10};
int n = sizeof (A) / sizeof(A[0]);
quicksort(A, &A[n-1]);
for (int i =0; i<n; i++) std::cout<<A[i] <<" ";
getchar();
return 0;
}
produces the output:
5 14 8 12 1 2 11 15 6 9 7 3 13 4 10
1 4 3 2 5 12 11 15 6 9 7 8 13 14 10
1 4 3 2
1 4 3 2
4 3 2
2 3 4
2 3
2 3
12 11 15 6 9 7 8 13 14 10
8 11 10 6 9 7 12 13 14 15
8 11 10 6 9 7
6 7 8 10 9 11
6 7
6 7
10 9 11
9 10 11
13 14 15
13 14 15
14 15
14 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15