關鍵點:向函數傳入數組首地址
#include <iostream>
using namespace std;
/*
冒泡排序
*/
void bubbleSort(int *arr,int length)
{
for (int i = 0; i < length - 1; i++)
{
for (int j = 0; j < length - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
/*
打印排序後的數組
*/
void printArray(int *arr, int length)
{
for (int i = 0; i < length; i++)
{
cout << arr[i] << endl;
}
}
int main()
{
int arr[] = { 2,1,4,3,6,5,8,7,10,9 };
int length = sizeof(arr) / sizeof(arr[0]);//數組長度
bubbleSort(arr,length);
printArray(arr, length);
system("pause");
return 0;
}
結果展示: