簡單插入排序

插入排序:
插入排序一般序列分爲兩部分,一部分已經排好序,另外是原始序列。從原始序列中取出第一個元素,插入到已經排好序的序列中。
下面是實現代碼
#include<iostream>
using namespace std;
void swap(int &a, int &b)
{
	int temp = a;
	a = b;
	b = temp;
}
void insert_sort(int arr[], int len)  //插入排序
{
	if (arr == NULL || len < 0)
		return;
	int i = 0, k = 0;
	for (i = 1; i < len; i++)
	{
		k = i;
		for (int j = i - 1; j >= 0 && k>=0; j--)
		{
			if (arr[k] >= arr[j]) //如果當前值比有序序列中的最大值大,則不移動元素,否則進行交換
			{
				break;
			}
			else
			{
				swap(arr[k], arr[j]);
				k--;


			}

		}
	}
}
int main()
{
	int arr[] = { 5, 4, 1, 7, 9, 8 };
	int num = 0;
	while (num++ != 10)
	{


		for (size_t i = 0; i < 6; i++)
		{
			arr[i] = rand() % 20;

		}
		insert_sort(arr, 6);
		for (size_t i = 0; i < 6; i++)
		{
			cout << arr[i] << "  ";
		}
		cout << endl;

	}
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章