sort algorithm

In the below sort algorithm, let's say left is 0 and right is 9 and v is an unsorted integer array from 0 to 9. At one part is sets left (0) to last. Then it sets i to left + 1, which is 1. If the element at position 2 is less than the element at position 1, then it does a swap. But the swap doesn't make sense because it first increments last to 1, and i is already equal to 1. Hence, we are passing 1 and a 1 to swap, which means it won't be swapping anything. Am I missing something here?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/* 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;
}
Topic archived. No new replies allowed.