插入排序
// 插入排序.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<stdio.h>
#include<windows.h>
void insertion_sort(int data[], int size);
void main()
{
int data[20];
int size = 0, i;
printf("\nPlease enter number to sort(enter 0 when end): \n");
printf("Number: ");
do //要求输入数据直到输入为0
{
scanf("%d",&data[size]);
} while (data[size++]!=0);
for (i = 0; i < 60; i++)
printf("-");
printf("\n");
insertion_sort(data,--size);
for (i = 0; i < 60; i++)
printf("-");
printf("\nSorting: ");
for (i = 0; i < size; i++)
printf("%d ",data[i]);
printf("\n");
system("pause");
}
void insertion_sort(int data[], int size)
{
int base, compare, temp, i;
for (base = 1; base < size; base++)//当数据小于第一个时,则插入前方,否则与后面数据对比找出插入位置
{
temp = data[base];
compare = base;
while (compare>0 && data[compare - 1] > temp)
{
data[compare] = data[compare - 1];
compare--;
}
data[compare] = temp;
printf("Access: ");
for (i = 0; i < size; i++)
printf("%d ",data[i]);
printf("\n");
}
}
运行结果: