插入排序(insertion sort)算法实现
2008-05-16 19:31
316 查看
插入排序算法的原理很简单,首先将数组的第一个数data[0]看成是有序的,然后从第二个元素开始和它前面的元素进行比较,如果从前面的某一个数大,就交换。由于前面的元素是有序的,所以就使有序元素的个数逐渐增大,直到等于n。插入排序的时间复杂度为O(n^2)。
算法的c实现如下:
#include <stdio.h>
void output_array(int data[], int n)
{
int i;
for(i = 0; i < n; i++)
printf("%d ", data[i]);
printf("\n");
}
void swap(int *a, int *b)
{
int x;
x = *a;
*a = *b;
*b = x;
}
//算法实现
void insertion(int data[], int b, int e)
{
int i, j;
for(i = b + 1; i <= e; i++)
{
for(j = i; j > 0 && data[j] > data[j - 1]; j--)
{
swap(&data[j], &data[j - 1]);
}
}
}
int main()
{
int data[] = {5, 3, 1, 665, 77, 66, 44, 11, 10, 9, 8, 6};
output_array(data, 12);
insertion(data, 0, 11);
output_array(data, 12);
return 0;
}
算法的c实现如下:
#include <stdio.h>
void output_array(int data[], int n)
{
int i;
for(i = 0; i < n; i++)
printf("%d ", data[i]);
printf("\n");
}
void swap(int *a, int *b)
{
int x;
x = *a;
*a = *b;
*b = x;
}
//算法实现
void insertion(int data[], int b, int e)
{
int i, j;
for(i = b + 1; i <= e; i++)
{
for(j = i; j > 0 && data[j] > data[j - 1]; j--)
{
swap(&data[j], &data[j - 1]);
}
}
}
int main()
{
int data[] = {5, 3, 1, 665, 77, 66, 44, 11, 10, 9, 8, 6};
output_array(data, 12);
insertion(data, 0, 11);
output_array(data, 12);
return 0;
}
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【147-Insertion Sort List(链表插入排序)】
- 算法从排序开始——插入排序(Insertion Sort)C语言及Java实现
- 算法学习记录-排序——插入排序(Insertion Sort)
- 【DS】排序算法之插入排序(Insertion Sort)
- 静态链表插入排序(List Insertion Sort)算法
- 【算法】插入排序 insertion_sort
- 算法:冒泡排序(Bubble Sort)、插入排序(Insertion Sort)和选择排序(Selection Sort)总结
- 【算法】插入排序(Insertion Sort)
- 算法-插入排序(Insertion Sort)
- [算法练习]Insertion Sort 插入排序
- Python 数据结构与算法——插入排序(insertion sort)
- 算法总结JS版(三)—— 插入排序(Insertion Sort)
- 算法:插入排序(Insertion Sort)
- 数据算法之插入排序(insertSort)的Java实现
- 经典算法(8)- 插入排序(Insertion Sort) 及三个基本排序算法的比较
- 【算法】插入排序 insertion_sort
- 插入排序 直接插入排序的PHP实现 Straight Insertion Sort
- 排序算法--插入排序(Insertion Sort)_C#程序实现
- 插入排序(INSERTION-SORT) PYTHON实现
- 数据算法之插入排序(insertSort)的Java实现