【排序算法模板】快速排序

 1 #include <iostream>

 2 #include <vector>

 3 using namespace std;

 4 

 5 void quickSort(vector<int>& nums, const int lpos, const int rpos)

 6 {

 7     if(lpos < rpos)

 8     {

 9         int low = lpos;

10         int high = rpos;

11         int key = nums[lpos];

12 

13         while(low < high)

14         {

15             while(low < high && nums[high] >= key)

16                 high--;

17 

18             if(low < high)

19                 nums[low++] = nums[high];

20 

21             while(low < high && nums[low] < key)

22                 low++;

23 

24             if(low < high)

25                 nums[high--] = nums[low];

26         }

27 

28         nums[low] = key;

29         quickSort(nums, lpos, low - 1);

30         quickSort(nums, low + 1, rpos);

31     }

32 }

33 

34 int main()

35 {

36     int a[] = {34,65,12,43,67,5,78,10,34,3,70};

37     vector<int> vec(a, a + 11);

38 

39     for(int i = 0; i < vec.size(); i++)

40         cout<<vec[i]<<" ";

41     cout<<endl;

42 

43     quickSort(vec, 0, 10);

44 

45     for(int i = 0; i < vec.size(); i++)

46         cout<<vec[i]<<" ";

47     cout<<endl;

48 

49 }

 

你可能感兴趣的:(快速排序)