quick sort not working.

can Someone tell me what is wrong with this code? I am so tired I cant think straight.

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
31
32
33
34
35
36
37
38
39
40
  void quickSort(std::vector<int>& a, int from, int to)
{
	if(from >= to) return;

	int p = partition(a, from, to);

	quickSort(a, from, p);
	quickSort(a, p + 1, to);
	
}


int partition(std::vector<int>& a, int from, int to)
{
	int pivot = a[from];

	int i = from - 1;
	int j = to + 1;

	while(i < j)
	{
		i++; if(a[i] < pivot) i++;
		j--; if(a[j] > pivot) j--;

		if(i < j)
		{
		swap(a[i], a[j]);
		}
		
	}

	return j;
}

void swap(int& a, int& b)
{
	int temp = a;
	a = b;
	b = temp;
}
1
2
3
4
5
6
7
8
9
10
11
	while(i < j)
	{
		i++; if(a[i] < pivot) i++;
		j--; if(a[j] > pivot) j--;

		if(i < j) //except for the last iteration this would always evaluate to true
		{
		swap(a[i], a[j]);
		}
		
	}
i relized why, I used if instead of a while loop.
Last edited on
Topic archived. No new replies allowed.