冒泡排序:
代码如下:
#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;
}