C++实现各种交换排序(冒泡,快速)
生活随笔
收集整理的這篇文章主要介紹了
C++实现各种交换排序(冒泡,快速)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
冒泡排序:
代碼如下:
#include <iostream> using namespace std;void BubbleSort(int *a, int len) {//數(shù)組下標從0開始for (int i = 1;i<=len-1;i++)//共需要len-1趟for (int j = 1; j <= len - i; j++)//第i趟的比較次數(shù)是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; }冒泡排序(優(yōu)化):
代碼如下:
#include <iostream> using namespace std;void BubbleSort(int *a, int len) {//數(shù)組下標從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趟的比較次數(shù)是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) {//數(shù)組下標從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; }總結(jié)
以上是生活随笔為你收集整理的C++实现各种交换排序(冒泡,快速)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中医讲上眼皮浮肿是什么原因
- 下一篇: 用棍子刮肚子会不会减肥