第一篇博客,好激动emmm。
言归正传,这篇博客是我对《算法导论》上快速排序算法的实践与一些思考。
首先贴出快速排序的坑爹的伪代码:
QuickSort(A,p,r)
if p<r
q = Partition(A,p,r)
QuickSort(A,p,q-1)
QuickSort(Q,q+1,r)
end
Partition(A,p,r)
x = A[r]
i = p-1
for j = p to r-1
if A[j] <= x
i = i+1
exchange A[i] <-> A[j]
exchange A[i+1]<->A[r]
return i+1
end
之后贴出对应的c++代码:
#include "stdafx.h"
#include<iostream>
#define N 10
using namespace std;
void quicksort(int A[], int low, int high);
int partition(int A[], int low, int high);
int main()
{
int A[N];
cout << "input ten number" << endl;
for (int i = 0; i < N; i++) {
cin >> A[i];
}
quicksort(A,0,N-1);
for (int i = 0; i < N; i++) {
cout << A[i] <<" ";
}
cout << endl;
return 0;
}
int partition(int A[], int low, int high){
int x = A[high];
int first = low - 1;
int temp;
for (int last = low; last < high; last++) {
if (A[last] <= x) {
first = first + 1;
temp = A[first];
A[first] = A[last];
A[last] = temp;
}
}
temp = A[first + 1];
A[first + 1] = A[high];
A[high] = temp;
return first+1;
}
void quicksort(int A[], int low, int high) {
if (low < high)
{
int middle = partition(A, low, high);
quicksort(A, low, middle - 1);
quicksort(A, middle + 1, high);
}
}
这里开始考虑代码中出现的问题:
1.虽然快速排序很简单,但是从伪代码到C++源代码需要注意这几点:
每个缩进代表一个函数的函数体具体内容。
注意for(;;)循环之后,循环变量值保持不变,循环变量最终值为“循环变量+1”
2.考虑函数中几个>=号,这几个符号我认为是由于快速排序具有不稳定性。因此可能出现low>=high的情况,另外low==high的确为判定结束的标志。
3.cin与scanf()相比,减少了指针“崩”的情况,C++大法好。