快速排序 c++

int partitions(vector &vec, int left, int right)
{
	int index = left;
	int base = vec[index];

	for (int i = index + 1; i <= right; i++)
	{
		if (vec[i] < base){
			index++;
			if (index != i)swap(vec[index], vec[i]);
		}
	}
	vec[left] = vec[index];
	vec[index] = base;

	return index;
}



void Qsort(vector &vec, int left, int right)
{
	if (left < right){
		int idx = partitions(vec,left, right);
		Qsort(vec,left ,idx-1 );
		Qsort(vec, idx+1, right);
	}
}


int main() {

	vector vec = { 21, 25, 49, 25, 16, 8 };
	Qsort(vec, 0, 5);

	for (int i = 0; i < 6; i++)
	{
		cout << vec[i] << endl;
	}

	//cout << res << endl;
	system("pause");
}

思想:先找一个基准,比如为0的位置。所有小于基准的元素移到基准的左边。大于基准的元素移到基准的右边。

你可能感兴趣的:(c++,算法)