//c++实现;
//冒泡排序;
void bubbleSort(int a[],int n)
{
for (int j = 0; j<n; j++)
{
for (int i = n-1; i>j; i--)
{
if (a[i] < a[i-1])
{
int temp = a[i-1];
a[i-1] = a[i];
a[i] = temp;
}
}
}
}
//插入排序;
void insertSort(int a[],int n)
{
int temp ;
for (int j = 0; j<n-1; j++)
{
temp = a[j+1];
int i = j;
while(i>=0 && temp<a[i])
{
a[i+1] = a[i];
i--;
}
a[i+1] = temp;
}
}
//选择排序;
void selectSort(int a[],int n)
{
for (int j = 0; j<n; j++)
{
for (int i = j+1; i<n; i++)
{
if (a[i]<a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
//基数排序;
void radixSort(int a[],int n)
{
int k = 1;
int d = 10;
for (int i = 0; i<n; i++) {
while (a[i]/d>0) {
k++;
d*=10;
}
}
int dx = 1;
int index = 0;
int *temp = new int[n];
for (int i = 1;i<=k; i++) {
index = 0;
for (int q = 0; q<10; q++) {
for (int j = 0; j<n; j++) {
if ((a[j]/dx)%10 == q) {
temp[index] = a[j];
index++;
}
}
}
for (int j = 0; j<n; j++) {
a[j] = temp[j];
}
dx*=10;
}
delete []temp;
}
//希尔排序;
void shellSort(int a[],int n)
{
int d = n/2;
while(d>=1)
{
for (int j = d; j<n; j++)
{
for (int i = j; i>=0; i-=d)
{
if (i-d>=0&&a[i]<a[i-d])
{
int iTemp = a[i];
a[i] = a[i-d];
a[i-d] = iTemp;
}
else
{
break;
}
}
}
d=d/2;
}
}
//快速排序;
void quickSort(int a[],int low,int high)
{
if (low >= high) {
return;
}
int first = low;
int last = high;
int key = a[first];
while (first<last) {
while (first<last&&a[last]>=key) {
last -- ;
}
int itemp = a[first];
a[first] = a[last];
a[last] = itemp;
while (first<last&&a[first]<=key) {
first ++;
}
itemp = a[first];
a[first] = a[last];
a[last] = itemp;
}
a[first] = key;
quickSort(a, low, first -1);
quickSort(a, first+1, high);
}
//归并排序;
void merge(int a[],int temp[],int s,int m,int e)
{
int i = s;
int j = m+1;
int k = s;
while (i<=m&&j<=e)
{
if (a[i]<a[j])
{
temp[k++] = a[i++];
}
else
{
temp[k++] = a[j++];
}
}
while (i<=m)
{
temp[k++] = a[i++];
}
while (j<=e)
{
temp[k++] = a[j++];
}
for (int q = s; q<=e; q++)
{
a[q] = temp[q];
}
}
void mergeSort(int a[],int temp[],int s,int e)
{
if(s>=e)return;
int m = (s+e)/2;
mergeSort(a, temp, s, m);
mergeSort(a, temp, m+1, e);
merge(a, temp, s, m, e);
}
//堆排序;
void heapMake(int a[],int i,int n)
{
int iL = 2*i+1;
int iR = iL+1;
while (i<n)
{
if (iR<n)
{
if (a[i]<=a[iL]&&a[i]<=a[iR]) {
return;
}
if (a[iL]<=a[iR]&&a[iL]<a[i]) {
int itemp = a[i];
a[i] = a[iL];
a[iL] = itemp;
i = iL;
iL = 2*i+1;
iR = iL+1;
}
else if(a[iR]<=a[iL]&&a[iR]<a[i])
{
int itemp = a[i];
a[i] = a[iR];
a[iR] = itemp;
i = iR;
iL = 2*i+1;
iR = iL+1;
}
}
else if(iL<n)
{
if (a[i]<=a[iL]) {
return;
}
if (a[iL]<a[i]) {
int itemp = a[i];
a[i] = a[iL];
a[iL] = itemp;
i = iL;
iL = 2*i+1;
iR = iL+1;
}
}
else
{
return;
}
}
}
void heapSort(int a[],int n)
{
for (int i = n-1; i>=0; i--) {
heapMake(a, i, n);
}
for (int j = n-1; j>=1; j--) {
int itemp = a[0];
a[0] = a[j];
a[j] = itemp;
heapMake(a,0,j);
}
}
八大排序
最新推荐文章于 2022-01-09 19:21:49 发布