编程语言
首页 > 编程语言> > C++插入排序(insertion sort)

C++插入排序(insertion sort)

作者:互联网

#include<iostream>
using namespace std;

void createArray(int* arr, int &n)
{
	cout << "Please enter the number of the array: ";
	cin >> n;
	cout << "Please enter the elements of the array: ";
	for (int i = 0;i < n; i++)
	{
		cin >> arr[i];
	}
}

void insertSort(int* arr, int n)
{
	for (int i = 1;i < n;i++)
	{
		for (int j = 0;j < i;j++)
		{
			int temp;
			if (arr[i] < arr[j])
			{
				temp = arr[i];
				arr[i] = arr[j];
				arr[j] = temp;
			}
		}
	}
}

void printArray(int* arr, int n)
{
	cout << "Now show the elements of the array: ";
	for (int i = 0;i < n;i++)
		cout << arr[i];
}

int main()
{
	int* arr = new int[50];
	int n;
	createArray(arr, n);
	insertSort(arr, n);
	printArray(arr, n);
	return 0;
}

标签:sort,arr,cout,temp,int,插入排序,++,insertion,void
来源: https://blog.csdn.net/qq_31617961/article/details/120253920