C语言实现排序算法

插入排序算法实现及时间复杂度分析

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值