插入排序算法实现及时间复杂度分析
1、直接插入排序
void insert_sort(int a[],int n){
int i,j,k;
int temp;
for(i=1;i<n;i++){
temp = a[i];
for(j=i-1;j>=0&&a[j]>temp;j--){
a[j+1] = a[j];
}
a[j+1] = temp;
}
}
直接插入排序原理:将一个记录插入到已经排好序的有序表中,是稳定的排序,平均时间复杂度为O(n2)
2、冒泡排序
void bubble_sort(int a[],int n){
int i,j;
int temp;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(a[j]>a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
冒泡排序原理:首先将第一个记录的关键字和第二个记录的关键字进行比较,若为逆序,则交换之,然后比较第二个和第三个元素。以此类推,直到第n-1和第n个关键字进行比较为止。每一趟冒泡排序都会挑出一个最大值。是稳定的排序,平均时间复杂度O(n2)
3、快速排序
int partition(int a[],int low,int high){
int pivotkey = a[low];
while(high>low){
while(high>low && a[high]>=pivotkey) --high;
{
int temp = a[high];
a[high] = a[low];
a[low] = temp;
}
while(high>low && a[low]<=pivotkey) ++low;
{
int temp = a[low];
a[low] = a[high];
a[high] = temp;
}
}
return low;
}
void quick_sort(int a[],int low,int high){
if(low<high){
int location = partition(a,low,high);
quick_sort(a,low,location-1);
quick_sort(a,location+1,high);
}
}
快速排序原理:通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分记录的关键字小,泽可分别对这两部分的记录继续进行排序,是不稳定的排序,平均时间复杂度为O(nlogn)
函数调用:
#include <stdio.h>
#define LENGTH(array) ( (sizeof(array)) / (sizeof(array[0])) )
int main(){
int array[] = {49,38,65,97,76,13,27};
int length = LENGTH(array);
//insert_sort(array,length);
//bubble_sort(array,length);
quick_sort(array,0,length-1);
int i;
for(i=0;i<length;i++){
printf("%d ",array[i]);
}
return 0;
}