- #include<stdio.h>
- #include<stdlib.h>
- //冒泡排序从小到大 第一趟得到最大的存到数组的最后,第二趟得到数组的第二大的,存到数组的倒数第二位。依次。。
- void bubble_sort(int *p){
- int length=6 ;
- for(int i=0;i<length;i++){
- for(int j=0;j<length-i;j++){
- if(p[j]>p[j+1]){
- int t;
- t=p[j];
- p[j]=p[j+1];
- p[j+1]=t;
- }
- }
- }
- //打印输出
- for(int i=0;i<length;i++){
- printf("%d\n",p[i]);
- }
- }
- //希尔排序
- void shell(int * p){
- int length=6;
- //取增量
- int step=length/2;
- while(step>=1){
- //无序序列
- for(int i=step;i<length;i++){
- int temp=p[i];
- int j;
- //有序序列
- for(j=i-step;j>=0 && temp<p[j];j=j-step){
- p[j+step]=p[j];
- }
- p[j+step]=temp;
- }
- step=step/2;
- }
- }
- //选择排序(选择出最小的假定第一个为最小的 然后判断 是否交换)
- void selection_sort(int *p){
- int length=6;
- int min,j,i,t;
- for(i=0; i<length;i++){
- for(min=i,j=i+1;j<length;j++){
- if(p[min]>p[j]){
- min=j;
- }
- }
- if(min!=i){
- t=p[i];
- p[i]=p[min];
- p[min]=t;
- }
- }
- //打印输出
- for(int i=0;i<length;i++){
- printf("%d\n",p[i]);
- }
- }
- //确定第一个数组元素的最终位置
- int find_pos(int *a,int low,int high){
- int val=a[low];
- while(low<high){
- while(low<high && a[high]>=val)
- --high;
- a[low]=a[high];
- while(low<high && a[low]<=val)
- ++low;
- a[high]=val;
- }
- a[low]=val;
- return low;
- }
- //快速排序 递归调用
- void quick_sort(int *a ,int low ,int high){
- int pos;
- if(low<high){
- pos=find_pos(a,low,high);
- quick_sort(a,low,pos-1);
- quick_sort(a,pos+1,high);
- }
- }
- //数组的两两合并操作,归并操作
- void merge(int *p,int *temp,int left,int middle,int right){
- //左指针尾
- int leftend=middle-1;
- //右指针头
- int rightstart=middle;
- //临时数组的下标
- int tempindex=left;
- //数组合并后的长度
- int templength=right-left+1;
- //先循环两个区间段都没有结束的情况
- while((left<=leftend)&&(rightstart<=right)){
- //r如果发现有序列小的,则将此数放入临时数组
- if(p[left]<p[rightstart]){
- temp[tempindex++]=p[left++];
- }else{
- temp[tempindex++]=p[rightstart++];
- }
- }
- //判断左边序列是否结束
- while(left<=leftend){
- temp[tempindex++]=p[left++];
- }
- //判断右边序列是否结束
- while(rightstart<=right){
- temp[tempindex++]=p[rightstart++];
- }
- //交换数据
- for(int i=0; i<templength;i++){
- p[right]=temp[right];
- right--;
- }
- }
- //归并排序 ---数组的划分
- void merge_sort(int *p ,int *temp,int left,int right){
- if(left<right){
- //取分割位置
- int middle=(left+middle)/2;
- //递归划分数组左序列
- merge_sort(p,temp,left,middle);
- //递归划分数组右序列
- merge_sort(p,temp,middle+1,right);
- //数组的合并操作
- merge(p,temp,left,middle+1,right);
- }
- }
- //插入排序
- void insert_sort(int *a){
- int len=6;
- int i, j, temp;
- for(i = 1; i < len; i ++)
- {
- temp = a[i];
- for(j = i - 1; j >= 0; j --)
- {
- if(a[j] > temp)
- {
- a[j + 1] = a[j];
- }else
- {
- break;
- }
- }
- a[j + 1] = temp;
- }
- }
- int main(int argc, char* argv[])
- {
- int a;
- int b[]={35,67,23,12,65,99};
- //bubble_sort(b);
- //selection_sort(b);
- //quick_sort(b,0,5);
- shell(b);
- //insert_sort(b);
- for(int i=0;i<6;i++){
- printf("%d\n",b[i]);
- }
- scanf("%a",&a);
- return 0;
- }
来源: http://www.phpxs.com/code/1004268/