插入排序-C语言

// 插入排序

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
#define ARR_SIZE(x) (sizeof(x)/sizeof(x[0]))

// 直接插入排序
void InsertSort(int arr[], int len);
// 折半插入排序
void BinaryInsertSort(int arr[], int len);
// 打印
void PrintSort(int arr[], int len);

int main(int argc, char** argv)
{
	// code
	int arr[] = { 2,1,3,6,4,8,7,6,9,5};

	//printf("%d\n", ARR_SIZE(arr));
	// 直接插入排序
	InsertSort(arr, ARR_SIZE(arr));
	PrintSort(arr, ARR_SIZE(arr));

	// 折半插入排序
	BinaryInsertSort(arr, ARR_SIZE(arr));
	PrintSort(arr, ARR_SIZE(arr));
	
	system("pause");
	return 0;
}

// 直接插入排序(升序。)
void InsertSort(int arr[], int len)
{
	int i, j, temp;

	for (i = 1; i < len; i++)  // 0号下标位置数据默认是已排好序的子序列,从下标1~len-1依次比较
	{
		temp = arr[i];  // 记录待比较的数据t=3  i=2
		for (j = i - 1; (temp < arr[j])&&(j>=0); j--)  // 在已排好序的子序列中从后往前查找,若大于temp,则执行循环体
		{
			arr[j + 1] = arr[j];  // 后移
		}
		arr[j + 1] = temp;  // 复制到要插入的位置。
	}
}

// 折半插入排序(降序)
void BinaryInsertSort(int arr[], int len)
{
	int i, j, low, high, mid, temp;
	for (i = 1; i < len; i++)
	{
		temp = arr[i];
		// 对已经排好序的子序列-折半查找待插入元素的位置
		low = 0;  // 子序列的最低位
		high = i - 1;  // 子序列的最高位
		while (low <= high)
		{
			mid = (low + high) / 2;  // 取中间值
			if (arr[mid] < temp)
			{
				high = mid - 1;  // 左半子表
			}
			else
			{
				low = mid + 1;  // 右半子表
			}
		}
		
		// 此时的high为temp的后继  arr[high] < temp < arr[high + 1]
		for (j = i - 1; j > high; j--)
		{
			arr[j + 1] = arr[j];  //// 后移。
		}

		arr[j + 1] = temp;
	}
}

void PrintSort(int arr[], int len)
{
	printf("arrSort: ");

	for (int i = 0; i < len; i++)
	{
		printf("%d  ", arr[i]);
	}
	printf("\n");
}

你可能感兴趣的:(数据结构)