算法导论快速排序算法实现:
1、算法导论快速排序文中例子:
#include <iostream>
using namespace std;
void quickSort(int A[], int p, int r);
int partition(int A[], int p, int r);
int main()
{
int A[] = {1, -4, -2, 3, 2, 4, 0,2,8};
int A_len = sizeof(A)/sizeof(int);
quickSort(A, 0, A_len-1);
cout<<A_len<<endl;
for(int i = 0; i <= A_len-1; i++)
{
cout<<A[i]<<endl;
}
return 0;
}
void quickSort(int A[], int p, int r)
{
if(p < r)
{
//cout<<" p : "<<p<<" r : "<<r<<endl;
int q = partition(A, p, r);
//cout<<q<<endl;
quickSort(A, p, q-1);
quickSort(A, q+1, r);
}
}
int partition(int A[], int p, int r)
{
int x = A[r];
int i = p;
for( int j = p; j <= r-1; j++)
{
if(A[j] <= x)
{
/**交换A[i], A[j]**/
//A[i] = A[i] + A[j];
//A[j] = A[i] - A[j];
//A[i] = A[i] - A[j];
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
i++;
}
}
//A[i] = A[i] + A[r];
//A[r] = A[i] - A[r];
//A[i] = A[i] - A[r];
//cout<<i<<endl;
int tmp1 = A[i];
A[i] = A[r];
A[r] = tmp1;
return i;
}
2、算法导论习题 7-2,针对相同元素的快速排序
#include <iostream>
#include "Poco/Random.h"
using namespace std;
struct tmpIndex
{
int q;
int t;
int left_same ;
int right_same ;
tmpIndex():q(0), t(0), left_same(1), right_same(1){}
};
void quickSort(int A[], int p, int r);
tmpIndex partition(int A[], int p, int r);
tmpIndex rendomPartition(int A[], int p, int r);
int main()
{
int A[] = {-1, 0, 0, 0, 0,9};
int A_len = sizeof(A)/sizeof(int);
quickSort(A, 0, A_len-1);
cout<<A_len<<endl;
for(int i = 0; i <= A_len-1; i++)
{
cout<<A[i]<<endl;
}
return 0;
}
void quickSort(int A[], int p, int r)
{
if(p < r)
{
//cout<<" p : "<<p<<" r : "<<r<<endl;
tmpIndex tmp_index = rendomPartition(A, p, r);
cout<<tmp_index.left_same<<endl;
cout<<tmp_index.right_same<<endl;
if(!tmp_index.left_same)
{
quickSort(A, p, tmp_index.q - 1);
}
if(!tmp_index.right_same)
{
quickSort(A, tmp_index.t, r);
}
}
}
tmpIndex rendomPartition(int A[], int p, int r)
{
/**Poco c++库**/
Poco::Random rnd(8);
rnd.seed();
int i;
if(p == 0)
i = rnd.next(r);
else
i = p + rnd.next(r - p);
cout<<" i : "<<i<<endl;
int tmp = A[r];
A[r] = A[i];
A[i] = tmp;
return partition(A, p, r);
}
tmpIndex partition(int A[], int p, int r)
{
tmpIndex tmp_index;
int x = A[r];
int i = p;
for( int j = p; j <= r-1; j++)
{
if(A[j] <= x)
{
/**交换A[i], A[j]**/
//A[i] = A[i] + A[j];
//A[j] = A[i] - A[j];
//A[i] = A[i] - A[j];
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
i++;
}
}
//A[i] = A[i] + A[r];
//A[r] = A[i] - A[r];
//A[i] = A[i] - A[r];
//cout<<i<<endl;
int tmp1 = A[i];
A[i] = A[r];
A[r] = tmp1;
/**与驱轴元素相同的值,出现在左边区域**/
int y = A[i];
int index = p;
//int left_same ;
for(int k = p; k <= i-1; k++)
{
if(A[k] != y)
{
int tmp = A[index];
A[index] = A[k];
A[k] = tmp;
index++;
}
}
tmp_index.q = index;
tmp_index.t = i + 1;
/**判断左右区间元素是否相同**/
for(int k = p+1; k <= tmp_index.q-1; k++)
{
if(A[k] != A[p])
{
tmp_index.left_same = 0;
break;
}
}
for(int k = tmp_index.t+1; k <= r; k++)
{
if(A[k] != A[tmp_index.t])
{
tmp_index.right_same = 0;
break;
}
}
return tmp_index;
}