摩托羅拉 G Pure 手機曝光:Helio G25 晶片,預計 1940 元起
阿新 • • 發佈:2021-09-27
交換排序
氣泡排序
氣泡排序程式碼演示:
給你一個n代表有n個數字,然後你需要使用氣泡排序將這些數字從小到大排好。
輸入描述:
第一行輸入一個n,代表有n個數字 第二行輸入n個數輸出描述:
輸出排序好後的n個數
示例1
輸入
4
4 3 2 1
輸出
1 2 3 4
#include <iostream>
#include <vector>
using namespace std;
void swap(int &p, int &q);
void bubbleSort(int *array, int n);
int main()
{
// 處理輸入資料
int n; // 資料個數
cin >> n;
int array[n];
for (int i = 0; i < n; ++i)
{
cin >> array[i];
}
// 氣泡排序
bubbleSort(array, n);
// 將陣列內資料列印
for (int i = 0; i < n; ++i)
{
cout << array[i] << " ";
}
return 0;
}
void bubbleSort(int *array, int n)
{
for (int i = 1; i < n; ++i) // 一共走n-1趟
{
for (int j = 0; j < n - i; ++j) // 每一趟將0到n-i內的最大值放到n-i處
{
if (array[j] > array[j+1])
{
swap(array[j], array[j+1]); // 交換資料
}
}
}
return;
}
void swap(int &p, int &q)
{
int tempVal = p;
p = q;
q = tempVal;
return ;
}