6-31 排序函数 (30分)

6-31 排序函数 (30分)
 

本题不限定排序算法,所给的数据集有种情况:

  1. 小规模(n<1000)无序数据;
  2. 小规模(n<1000)递增数据;
  3. 小规模(n<1000)递减数据;
  4. 大规模(10000<n<1000000)无序数据;
  5. 大规模(10000<n<1000000)递增数据;
  6. 大规模(10000<n<1000000)递减数据。

结果按照从小到大排序。数据均为32位int的全部范围。

本题禁止使用C标准库的heapsort、heapsort_b、mergesort、mergesort_b、qsort、qsort_b和qsort_r。

函数接口定义:

void sort ( int a[], int len );
 

这里a是要排序的数组,len是数组长度。

裁判测试程序样例:

#include <stdio.h>

void sort ( int a[], int len );

int main(void)
{
	int n;
	scanf("%d", &n);
	int a[n];
	for ( int i=0; i<n; i++ ) {
		scanf("%d", &a[i]);
	}
	
	sort(a, n);

	for ( int i=0; i<n; i++ ) {
		printf("%d\n", a[i]);
	}
}

/* 请在这里填写答案 */
 

输入样例:

5
1
2
3
1
4
 

输出样例:

1
1
2
3
4


这题明显要使用快排才可以,我进一步将快排优化了一下,因为数据里边有递增而且是大数,这对
传统快排来说是致命的,因为快排会退化为o(n2),我对此的优化是三数取中值,就是从头和中还有末
三个数当中取中间值,第二当数组划分个数不多的时候,大概15个以下,其实插入排序更好。对此进行优化。
然后将一些循环变量变成register能快一些。

void insertsort(int a[],int low,int high)
{
 int temp;
 register int i,j;
 for(i=low+1;i<=high;i++)
 {
  temp=a[i];
  for(j=i-1;j>=low&&a[j]>temp;j--)
  {
   a[j+1]=a[j];
  }
  a[j+1]=temp;
 
  
 }
 
}
void swap(register int *a,register int *b)    
{
   register int temp;
 temp=*a;
 *a=*b;
 *b=temp;
 }
void  partion(int a[],register int low ,register int high)
{
 if(high-low<15)
 {
 insertsort(a,low,high);
 return ;
    }
 int s;
 int temp;
 s=(low+high)/2;
 if(a[s]>a[low])
 {
  swap(a+s,a+low);
 }
 if(a[s]>a[high])
 {
  swap(a+s,a+high);
 }
 if(a[low]>a[high])
 swap(a+low,a+high);
 
 
 
  
 s=a[low];
 register int i=low,j=high;
 while(i<j)
 {
  while(i<j&&a[j]>=s)j--;
  
   
   a[i]=a[j];
   
  
  while(i<j&&a[i]<=s)i++;
   a[j]=a[i];
   
 }
 a[i]=s;
 partion(a,low,i-1);
 partion(a,i+1,high);
 }
void sort(int a[],int len)
{
 
 partion(a,0,len-1);
 
}


posted @ 2020-10-19 21:03  罪梦者  阅读(435)  评论(0)    收藏  举报