(4) Sorting algorithm: quick sort

The idea of ​​quick sorting:
    select a number in the array as the central axis, and then use the central axis as the center, place the data larger than the central axis on the right, and place the data smaller than the central axis on the left,
    and then change the center after each comparison. The position of the axis, keep comparing
 

Code:

#include <iostream>

using namespace std;



template <class T>
void quick_sort(T arry[], int left, int right)
{
	if (left < right)
	{
		int i = left;
		int j = right + 1;

		T pivot = arry[left]; //选左边的为中轴线

		do
		{
			do i++; while (arry[i] < pivot);
			do j--; while (arry[j] > pivot);
			if(i < j)
				swap(arry[i],arry[j]);
		} while (i < j);

		swap(arry[left],arry[j]); //改变中轴线的位置

		quick_sort(arry,left,j-1);
		quick_sort(arry,j+1,right);
	}

	

}


int main()
{
	int arry[12] = { 7,8,9,0,11,4,5,6,1,2,3 ,9999};

	quick_sort(arry, 0, 11);

	for (int i = 0; i < 11; i++)
		cout << arry[i] << " ";

	cout << endl << endl << endl;
	return 0;
}

operation result:

 

 

Guess you like

Origin blog.csdn.net/weixin_40204595/article/details/106764859