C++篇——C++實作冒泡排序和選擇排序演算法
- 摘要
- 冒泡法
- 代碼
- 運行結果
- 選擇排序法
- 代碼
- 運行結果
摘要
本文通過C++實作了兩類基礎且經典的排序演算法(冒泡法和選擇排序法),
冒泡法
代碼
#include <iostream>
using namespace std;
int main()
{
/** 需要排序的陣列 */
double array[] = {5.8,2.3,4.9,10.8,-50.2,20.4,19.5,23.8,10.9,100.2};
/** 陣列的長度 */
int array_length = sizeof(array)/sizeof(double);
cout << "length of array is : " << array_length << endl;
// 冒泡法進行降序排序
double temp;
for(int i = 0; i < array_length-1; i++){
for(int j=0; j < array_length-i-1; j++){
if(array[j]<array[j+1]){
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
// 輸出排序結果
int i = 0;
while( i < array_length){
cout << array[i] << "\t";
i ++ ;
}
cout << endl;
}
運行結果
length of array is : 10
100.2 23.8 20.4 19.5 10.9 10.8 5.8 4.9 2.3 -50.2
選擇排序法
代碼
#include <iostream>
using namespace std;
int main()
{
/** 需要排序的陣列 */
double array[] = {5.8,2.3,4.9,10.8,-50.2,20.4,19.5,23.8,10.9,100.2};
/** 陣列的長度 */
int array_length = sizeof(array)/sizeof(double);
cout << "length of array is : " << array_length << endl;
// 選擇排序法進行排序
double temp;
for(int i=0; i < array_length - 1; i++){
for(int j=i+1; j < array_length; j ++ )
{
if(array[j] > array[i]){
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
// 輸出排序結果
int i = 0;
while( i < array_length){
cout << array[i] << "\t";
i ++ ;
}
cout << endl;
}
運行結果
length of array is : 10
100.2 23.8 20.4 19.5 10.9 10.8 5.8 4.9 2.3 -50.2
by CyrusMay 2021 01 18
一顆葡萄有多甜美
用盡了所有的
圖騰和語言
描寫
——————五月天(倉頡)——————
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/250687.html
標籤:其他
上一篇:單鏈表的實作以及相關操作
下一篇:萬字長文爆肝 DNS 協議!
