zoukankan      html  css  js  c++  java
  • 几种常见排序的代码和时间比较

    void	my_sort(int n)		//冒泡	耗时15499ms
    {
    	for(int i = 0;i < n;i ++)
    		for(int j = 0;j < n - i - 1;j ++)
    			if(s[j] > s[j + 1])
    				swap(s[j],s[j + 1]);
    }
    

    void	my_sort(int n)		//选择	耗时3580ms
    {
    	for(int i = 0;i < n;i ++)
    	{
    		int	min_index = i;
    		for(int j = i;j < n;j ++)
    			if(s[j] < s[min_index])
    				min_index = j;
    		swap(s[min_index],s[i]);
    	}
    }
    

    void	my_sort(int n)		//插入	耗时2809ms
    {
    	int	i,j;
    	for(i = 1;i < n;i ++)
    	{
    		int	temp = s[i];
    		for(j = i - 1;j >= 0 && s[j] > temp;j --)
    			s[j + 1] = s[j];
    		s[j + 1] = temp;
    	}
    }
    

    void	my_sort(int left,int right)		//归并	耗时171ms
    {
    	if(left >= right)
    		return	;
    
    	int	length = right - left;
    	int	mid = left + (length >> 1);
    	int	start_1 = left,end_1 = mid;
    	int	start_2 = mid + 1,end_2 = right;
    
    	my_sort(start_1,end_1);
    	my_sort(start_2,end_2);
    
    	int	k = left;
    	while(start_1 <= end_1 && start_2 <= end_2)
    		TEMP[k ++] = s[start_1] < s[start_2] ? s[start_1 ++] : s[start_2 ++];
    	while(start_1 <= end_1)
    		TEMP[k ++] = s[start_1 ++];
    	while(start_2 <= end_2)
    		TEMP[k ++] = s[start_2 ++];
    
    	for(k = left;k <= right;k ++)
    		s[k] = TEMP[k];
    }
    

    void	my_sort(int left,int right)		//快排	耗时168ms
    {
    	if(left >= right)
    		return	;
    
    	int	key = s[right];
    	int	small_index = left;
    	for(int i = left;i <= right;i ++)
    		if(s[i] < key)
    		{
    			swap(s[small_index],s[i]);
    			small_index ++;
    		}
    	if(s[small_index] > key)
    		swap(s[right],s[small_index]);
    
    	my_sort(left,small_index - 1);
    	my_sort(small_index + 1,right);
    }
    





  • 相关阅读:
    Gym
    [APIO2014] 回文串
    python选课系统
    python面向对象之类成员修饰符
    python面向对象之类成员
    python的shelve模块
    python的re模块
    python的configparser模块
    python的sys和os模块
    python的hashlib模块
  • 原文地址:https://www.cnblogs.com/xz816111/p/5348097.html
Copyright © 2011-2022 走看看