快速排序算法实现
用python实现
def Partition(A,p,q):
x=A[p]
i=p
j=q
while True:
while i<j and A[j]>=x:
j=j-1
if i<j:
A[i],A[j]=A[j],A[i]
while i<j and A[i]<=x:
i=i+1
if i<j:
A[i],A[j]=A[j],A[i]
else:
A[p],A[j]=A[j],A[p]
return j
def QuickSort(A,p,r):
if p<r:
q=Partition(A,p,r)
A[p],A[q]=A[q],A[p]
QuickSort(A,p,q-1)
QuickSort(A,q+1,r)
def main():
A=[5,2,4,3,2,9,9,7,8,7]
QuickSort(A,0,len(A)-1)
print(A)
if __name__=='__main__':
main()
用matlab实现
function res=Partition(A,p,r)
x=A(p);
i=p;
j=r;
while true
while i<j && A(j)>=x
j=j-1;
end
if i<j
t=A(i);
A(i)=A(j);
A(j)=t;
end
while i<j && A(i)<=x
i=i+1;
end
if i<j
t=A(i);
A(i)=A(j);
A(j)=t;
else
t=A(p);
A(p)=A(j);
A(j)=t;
res=j;
break;
end
end
function A=QuickSort(A,p,r)
if p<r
q=Partition(A,p,r);
t=A(p);
A(p)=A(q);
A(q)=t;
A=QuickSort(A,p,q-1);
A=QuickSort(A,q+1,r);
end
A=input('Input An Array To Begin QuickSort:')
[row,len]=size(A);
A=QuickSort(A,1,len)
用C++实现
#include<iostream>
#include<algorithm>
using namespace std;
int Partition(int A[], int p, int r) {
int x = A[p];
int i = p;
int j = r;
while(true){
while (i < j && A[j] >= x) {
j--;
}
if (i < j) {
swap(A[i], A[j]);
}
while (i < j && A[i] <= x) {
i++;
}
if (i < j) {
swap(A[i], A[j]);
}
else {
break;
}
}
swap(A[p], A[j]);
return j;
}
void QuickSort(int A[], int p, int r) {
if (p < r) {
int q = Partition(A, p, r);
swap(A[p], A[q]);
QuickSort(A, p, q - 1);
QuickSort(A, q + 1, r);
}
}
void print(int A[], int len) {
for (int i = 0; i < len; i++) {
cout << A[i] << " ";
}
cout << endl;
}
int main() {
int A[10] = { 5, 2, 4, 3, 2, 9, 9, 7, 8, 7 };
print(A, sizeof(A) / sizeof(int));
QuickSort(A, 0, sizeof(A) / sizeof(int) - 1);
print(A, sizeof(A) / sizeof(int));
return 0;
}
转载请注明原文地址:https://blackberry.8miu.com/read-27558.html