数据结构-常见10种排序算法及对比
一、对比
二、排序算法
1.冒泡排序
#include <iostream>
using namespace std;
int* bubbleSort(int innum[],int len,int order)
{
for (int i = 0;i < len-1;i++) {
for (int j = 0;j < len-1;j++) {
if ((innum[j] > innum[j + 1])&&(0==order)) {
int tran = innum[j + 1];
innum[j + 1] = innum[j];
innum[j] = tran;
}
else if ((innum[j] < innum[j + 1])&&(1==order)) {
int tran = innum[j + 1];
innum[j + 1] = innum[j];
innum[j] = tran;
}
}
}
return innum;
}
int main()
{
int num1[] = { 4,3,5,1,0,45,30,20,34,55,70,7 };
int num2[] = { 10,4,5,9,0,45,30,20,34,55,88,7,90,120,1,2 };
int len1 = sizeof(num1)/ sizeof(num1[0]);
int len2 = sizeof(num2) / sizeof(num2[0]);
int *sortAscendingorder = bubbleSort(num1, len1, 0);
cout << "sortAscendingorder--> "<< endl;
for (int i = 0;i < len1;i++)cout << sortAscendingorder[i]<<" ";
cout << endl;
int* sortDescendingorder = bubbleSort(num2, len2, 1);
cout << "sortDescendingorder--> " << endl;
for (int i = 0;i < len2;i++)cout << sortDescendingorder[i]<<" ";
cout << endl;
}
2.快速排序
#include <iostream>
using namespace std;
void swap(int* a, int* b)
{
int tran = *a;
*a = *b;
*b = tran;
}
int partitionPosition(int innum[], int left, int right)
{
int middle = innum[left];
int lp = left + 1;
int rp = right;
while (true) {
while ((lp <= rp) && (innum[lp] <= middle))lp++;
while ((lp <= rp) && (innum[rp] >= middle))rp--;
if (lp >= rp)break;
swap(innum[lp], innum[rp]);
}
int lastlessMiddle = innum[rp];
innum[left] = lastlessMiddle;
innum[rp] = middle;
return rp;
}
int* quickSort(int innum[], int left, int right)
{
if (left < right) {
int midpos = partitionPosition(innum, left, right);
innum = quickSort(innum, left, midpos - 1);
innum = quickSort(innum, midpos + 1, right);
}
return innum;
}
int main()
{
int num1[] = { 4,3,5,1,0,45,30,20,34,55,70,7 };
int num2[] = { 10,4,5,9,0,45,30,20,34,55,88,7,90,120,1,2 };
int n1 = sizeof(num1) / sizeof(num1[0]);
int n2 = sizeof(num2) / sizeof(num2[0]);
int* sortQuick = quickSort(num1, 0, n1 - 1);
cout << "sortQuick--> " << endl;
for (int i = 0;i < n1;i++)cout << sortQuick[i] << " ";
cout << endl;
int* sortQuick2 = quickSort(num2, 0, n2 - 1);
cout << "sortQuick2--> " << endl;
for (int i = 0;i < n2;i++)cout << sortQuick2[i] << " ";
cout << endl;
return 0;
}