Hi, i found this piece of code in K&R book, but i have not understood how it works, page 74,
for example, what represent "int left, int right" variables and how should i use it?
I know this is not the complete qsort code inside standard library.
Code:
/* qsort: sort v[left]...v[right] into increasing order */
void qsort(int v[], int left, int right)
{
int i, last;
void swap(int v[], int i, int j);
if (left >= right) /* do nothing if array contains */
return;
/* fewer than two elements */
swap(v, left, (left + right)/2); /* move partition elem */
last = left;
/* to v[0] */
for (i = left + 1; i <= right; i++) /* partition */
if (v[i] < v[left])
swap(v, ++last, i);
swap(v, left, last);
/* restore partition elem */
qsort(v, left, last-1);
qsort(v, last+1, right);
}
/* swap: interchange v[i] and v[j] */
void swap(int v[], int i, int j)
{
int temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
i tried to implement it :
I renamed qsort to quicksort, because it conflicts with the qsort in the standard library.
Code:
#include <stdio.h>
void qicksort( int v[], int left, int right );
int main(void) {
int arr[] = { 3, 5, 1, 2, 4 };
qsort( arr, 0, 5 );
int i;
for ( i = 0; i < 5; i++ )
printf("num=%d\n", arr[i] );
}
/* qsort: sort v[left]...v[right] into increasing order */
void qicksort(int v[], int left, int right) {
int i, last;
void swap(int v[], int i, int j);
if (left >= right) /* do nothing if array contains */
return;
/* fewer than two elements */
swap(v, left, (left + right)/2); /* move partition elem */
last = left;
/* to v[0] */
for (i = left + 1; i <= right; i++) /* partition */
if (v[i] < v[left])
swap(v, ++last, i);
swap(v, left, last);
/* restore partition elem */
qicksort(v, left, last-1);
qicksort(v, last+1, right);
}
/* swap: interchange v[i] and v[j] */
void swap(int v[], int i, int j) {
int temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}