插入排序C++

1、算法描述

/*
变量:
i=1..............代表待插入数字的下标;
preIndex.........代表前一个元素的下标;
length...........代表数组的长度
排序过程:
arr[0]跳过,从arr[1]开始,每一个数都和它前面的数字比较。
while(i<length){//遍历数组arr[1]...arr[length-1]
	preIndex=i-1
	若arr[preIndex]<=arr[i],那么前小后大,有序,i++
	若arr[preIndex]>arr[i],那么前大后小,乱序
	{
		current=arr[i]//记录下待插入的数值
		arr[i]=arr[preIndex]
		preIndex--;
	while(preIndex>=0&&arr[preIndex]>tem)//preIndex不小于0且arr[preIndex]>tem
	{
		arr[preIndex+1]=arr[preIndex]
		preIndex--
	}
	arr[preIndex+1]=current;
	i++;

}
}
*/

2、C++实现

void insertsort(int arr[],int length) {
	int i = 1;
	while (i<length)
	{
		int preIndex = i - 1;
		if (arr[preIndex] > arr[i])//前大后小
		{
			int current = arr[i];//记录待插入的数值
			while (preIndex >= 0 && arr[preIndex] > current)
			{
				arr[preIndex + 1] = arr[preIndex];//将arr[preIndex]后移一位
				preIndex = preIndex - 1;
			}
			arr[preIndex + 1] = current;
		}
		i += 1;
		
	}
}
int main() {
	int arr[] = { 9,3,1,18,3,2,1,0,13,18,100 };
	int length = sizeof(arr) / sizeof(arr[0]);
	cout << "排序前数组为:" << endl;
	for (int i = 0; i < length; i ++) {
		cout << arr[i];
		cout << "\t";
	}
	cout << endl;
	insertsort(arr, length);
	cout << "排序后数组为:" << endl;
	for (int i = 0; i < length; i++) {
		cout << arr[i];
		cout << "\t";
	}
	system("PAUSE");

}

猜你喜欢

转载自blog.csdn.net/u013521296/article/details/88084794
今日推荐