//sort.pl #!/usr/bin/perl use strict; use warnings; open OUT, "> sort_list"; my $total=1000; my ($i,$j); select OUT; for($i=0;$i<$total/10;$i++) { for($j=0;$j<10;$j++){ my $num=int(rand(1000)); print "$num "; } print "/n"; } close OUT //sort.c #include<stdio.h> void insertSort(int *a,int len) { int i,j; for(i=1;i<len;i++){ int tmp=a[i]; for(j=i-1;j>=0;j--){ if(tmp<a[j]){ a[j+1]=a[j]; } else{ break; } } a[j+1]=tmp; } } void BinsertSort(int *a,int len){ int i; for(i=1;i<len;i++){ int low=0; int high=i-1; int tmp=a[i]; while(low<=high){ int mid=(low+high)/2; if(a[mid]<tmp)low=mid+1; else high=mid-1; } int j; for(j=i-1;j>=high+1;j--){ a[j+1]=a[j]; } a[high+1]=tmp; } } void bubbleSort(int *a,int len){ int i,j; for(i=0;i<len;i++){ int flag=0; for(j=len-1;j>i;j--){ if(a[j]<a[j-1]){ int t=a[j-1]; a[j-1]=a[j]; a[j]=t; flag=1; } } if(flag==0)break; } } int partition(int *a,int low,int high) { int t=a[low]; while(low<high){ while(low<high&&a[high]>=t){high--;} a[low]=a[high]; while(low<high&&a[low]<=t){low++;} a[high]=a[low]; } a[low]=t; return low; } //a[high] should be accessed; void quickSort(int *a,int low,int high){ if(low<high){ int mid=partition(a,low,high); quickSort(a,low,mid-1); quickSort(a,mid+1,high); } } void heapAdjust(int *a,int len){ int i=(len-2)/2; //adjust from the last node which is not a leaf; while(i>=0){ int j=2*i+1; if(j+1<=len-1&&a[j]<a[j+1]){ j++; } if(a[i]<a[j]){ int t=a[i]; a[i]=a[j]; a[j]=t; } i--; } } void heapSort(int *a,int len){ int i; for(i=len-1;i>0;i--){ heapAdjust(a,i); //swap a[0] a[i] int t=a[i]; a[i]=a[0]; a[0]=t; } } void merge(int *a,int p,int q,int r){ int len1=q-p; int len2=r-q+1; int s1[len1]; int s2[len2]; int i;int j=0; for(i=p;i<q;i++){ s1[j++]=a[i]; } j=0; for(i=q;i<=r;i++){ s2[j++]=a[i]; } i=0;j=0;int k=p; while(i<len1&&j<len2){ if(s2[j]<s1[i]){a[k++]=s2[j];j++;} else {a[k++]=s1[i];i++;} } while(i<len1){a[k++]=s1[i++];} while(j<len2){a[k++]=s2[j++];} } void mergeSort(int *a,int p,int r){ if(p<r){ int q=(p+r)/2; mergeSort(a,p,q); mergeSort(a,q+1,r); merge(a,p,q+1,r); } } int main() { FILE *fp; fp=fopen("./sort_list","r"); if(fp==NULL){ printf("cannot open file !/n"); exit(-1); } int a[1000]; int i; for(i=0;i<100;i++){ fscanf(fp,"%d",&a[i]); } fclose(fp); printf("before sort:/n"); for(i=0;i<100;i++){ printf ("%4d/t",a[i]); } printf("/nafter sort:/n"); mergeSort(a,0,99); printf("/n"); for(i=0;i<100;i++){ printf ("%4d/t",a[i]); } printf("/n"); return 0; }
因为面试经常考排序,所以写了些. 代码经过测试可以运行.
几种常见的排序
最新推荐文章于 2024-08-12 07:53:05 发布