生活随笔
收集整理的這篇文章主要介紹了
快速排序(c++)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、快速排序的思想
快速排序就是給基準數據找在數組中正確位置的過程,一旦基準位置的正確位置找到,那基準位置左右兩邊經過同樣的步驟遞歸也可以有序,最終整體數組有序。
整體可以理解為三個步驟:
1、先從隊尾開始向前掃描且當l < r時,如果a[r] > temp ,則r – ,如果a[r] < temp ,則將r的值賦給l, 即a[l] = a[r] ,賦值后必轉換掃描方向,即從隊首向隊尾掃描 ;
2、從隊首向隊尾掃描時且當l < r, 如果a[l] < temp , 則l ++ , 如果a[l] > temp ,則將l的值賦給r, 即a[r] = a[l] ,賦值后必轉換掃描方向,即從隊尾想隊首掃描 ;
3、不斷重復步驟1和2 ,直到l = r時,l或r的位置就是該基準數據在數組中的正確索引位置。
#include<iostream>
using namespace std
;
int partition(int *a
,int l
,int r
)
{int i
= l
+1; int j
= r
;int temp
= a
[l
];while (1){while (a
[i
] < temp
&& i
< r
){i
++;}while (a
[j
] > temp
){j
--;}if (i
>= j
)break;swap(a
[i
], a
[j
]);}swap(a
[l
], a
[j
]);return j
;
}
void quick(int* a
,int l
,int r
)
{if (l
< r
){int q
= partition(a
, l
, r
);quick(a
, l
, q
-1);quick(a
, q
+1 , r
);}
}
void main()
{int a
[10]{ 2,1,5,3,4,9,6,8,7,0 };quick(a
,0,9);for (int i
= 0; i
< 10; i
++){cout
<< a
[i
];}
}
下面是第二中方法,只不過是j的位置不同而已,原理是一致的
#include<iostream>
using namespace std
;
int q_step2(int* a
, int f
, int l
)
{int value
= a
[l
];int i
= f
;int j
= i
;for (j
; j
< l
; j
++){if (a
[j
] < value
){swap(a
[i
], a
[j
]);i
++;}}swap(a
[i
], a
[l
]);return i
;
}void q_step1(int* a
, int f
, int l
)
{if (f
>= l
)return;int q
= q_step2(a
, f
, l
);q_step1(a
, f
, q
- 1);q_step1(a
, q
+ 1, l
);}
void main()
{int a
[10]{ 2,1,5,3,4,9,6,8,7,0 };q_step1(a
,0,9);for (int i
= 0; i
< 10; i
++){cout
<< a
[i
];}
}
總結
以上是生活随笔為你收集整理的快速排序(c++)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。