C++实现各种交换排序(冒泡,快速)
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++实现各种交换排序(冒泡,快速)相关的知识,希望对你有一定的参考价值。
冒泡排序:
代码如下:
#include <iostream>
using namespace std;
void BubbleSort(int *a, int len)
{//数组下标从0开始
for (int i = 1;i<=len-1;i++)//共需要len-1趟
for (int j = 1; j <= len - i; j++)//第i趟的比较次数是len-i次
if (a[j - 1] > a[j])
{
int temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
int main()
{
int a[] = { 1231,34,532,5,4,124,214,12,3,14 };
BubbleSort(a, 10);
for (int i = 0; i < 10; i++) cout << a[i] << " ";
cout << endl;
return 0;
}
冒泡排序(优化):
代码如下:
#include <iostream>
using namespace std;
void BubbleSort(int *a, int len)
{//数组下标从0开始
bool flag = true;
for (int i = 1; i <= len - 1 && flag; i++)//共需要len-1趟
{
flag = false;
for (int j = 1; j <= len - i; j++)//第i趟的比较次数是len-i次
if (a[j - 1] > a[j])
{
flag = true;
int temp = a[j - 1];
a[j - 1] = a[j];
a[j] = temp;
}
}
}
int main()
{
int a[] = { 1,3,54,554,4264,5234,68658,70000,88888,999999 };
BubbleSort(a, 10);
for (int i = 0; i < 10; i++) cout << a[i] << " ";
cout << endl;
return 0;
}
快速排序:
代码如下:
#include <iostream>
using namespace std;
int Partition(int *a, int low, int high);
void QSort(int *a, int low, int high)
{//数组下标从1开始
if (low < high)
{
int pivotloc = Partition(a, low, high);
QSort(a, low, pivotloc - 1);
QSort(a, pivotloc + 1, high);
}
}
int Partition(int *a, int low, int high)
{
a[0] = a[low];
int pivotkey = a[low];
while (low < high)
{
while (low < high && a[high] >= pivotkey) --high;
a[low] = a[high];
while (low < high && a[low] <= pivotkey) ++low;
a[high] = a[low];
}
a[low] = a[0];
return low;
}
int main()
{
int a[] = { 0,123,14124,4,214,23,4,324,24,124,24 };
QSort(a, 1, 10);
for (int i = 1; i <= 10; i++) cout << a[i] << " ";
cout << endl;
return 0;
}
以上是关于C++实现各种交换排序(冒泡,快速)的主要内容,如果未能解决你的问题,请参考以下文章