天天看點

C++——指針配合數組和函數案例

C++——指針配合數組和函數案例

目标:封裝一個函數,實作對整型數組的升序冒泡排序

#include<iostream>
using namespace std;

//建立一個升序冒泡函數  參數1 數組的首位址  參數2 數組長度
void bubbleSort(int *arr,int len)
{
	for (int i = 0; i < len - 1; i++)
	{
		for (int j = 0; j < len - i - 1; j++)
		{
			//如果j>j+1的值,交換數字
			if (arr[j] > arr[j + 1])
			{
				int temp = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = temp;
			}
		}
	}
}

//顯示數組函數
void arrayPrint(int *arr,int len)
{
	for (int i = 0; i < len; i++)
	{
		cout << arr[i] << endl;
	}

}
int main()
{
	//封裝一個函數,實作對整數型數組的升序排列
	//建立一個數組
	int arr[10] = { 1,7,2,8,3,9,4,10,5,6 };
	//數組長度
	int len = sizeof(arr) / sizeof(arr[0]);
	//實作冒泡排序
	bubbleSort( arr,len);
	//列印數組
	arrayPrint(arr,len);

	system("pause");
	return 0;
}
           
C++——指針配合數組和函數案例