- #include <stdio.h>
- void bubbleSort(int *list,int index)
- {
- int i,j;
- int temp;
- for(j=index;j>0;j--)
- {
- for(i=0;i<j-1;i++)
- {
- if(list[i]>list[i+1])
- {
- temp=list[i+1];//较小值保存在暂存变量里
- list[i+1] = list[i];// 较大值后移
- list[i] = temp;//较小值前移
- }
- }
- }
- }
- void quicksort(int *list,int left,int right)
- {
- int i,j,k;
- int pivot;//分割指针
- int temp;//交换时的暂存变量
- i=left;j=right+1;
- pivot=list[left];
- if(i<j)
- {
- do
- {
- do
- {
- i++;
- }while(list[i]<=pivot&&i<=right);//从左往右找大于pivot的值
- do
- {
- j--;
- }while(list[j]>=pivot&&j>left);//从右往左找小于pivot的值
- if(i<j)
- {
- temp=list[i];
- list[i] = list[j];
- list[j] = temp;
- }
- }while(i<j);//1st do
- temp = list[left];
- list[left] = list[j];
- list[j] = temp;
- quicksort(list,left,j-1);
- quicksort(list,j+1,right);
- }
- }
- void selectionsort(int *list,int index)
- {
- int i,j,minat,min;
- for(i=0;i<(index-1);i++)
- {
- minat=i;
- min = list[i];
- for(j=i+1;j<index;j++)//select the min of the rest of array
- {
- if(min>list[j])
- {
- minat = j;//position of the min element
- min=list[j];
- }
- }
- int temp=list[i];
- list[i]=list[minat];
- list[minat] = temp;
- }
- }
- void insertionsort(int *list,int index)
- {
- int i,j;
- int insertnode;
- for(i=1;i<index;i++)
- {
- insertnode=list[i];//设置欲插入的数值
- j=i-1;
- while(j>=0&&insertnode<list[j])
- {
- list[j+1] = list[j];
- j--;
- }
- list[j+1] = insertnode;
- }
- }
- void shellsort(int *list,int index)
- {
- int i,j,d;
- int temp;
- d=index/2;//初始集合间隔长
- while(d>0)
- {
- for(i=d;i<index;i++)
- {
- j=i-d;
- while(j>=0)
- {
- if(list[j]>list[j+d])
- {
- temp=list[j];
- list[j]= list[j+d];
- list[j+d]= temp;
- j=j-d;
- }
- else
- j=-1;
- }
- }
- d/=2;
- }
- }
- int main()
- {
- int bsort[64];
- int i,node,index=0;
- printf("Please input number to sort:/n");
- scanf("%d",&node);
- while(node)
- {
- bsort[index++]=node;
- scanf("%d",&node);
- }
- /*-------------Bubble Sort-------------------*/
- //bubbleSort(bsort,index);
- /*------------------------------------------*/
- /*----------quick sort----------------------*/
- //quicksort(bsort,0,index-1);
- /*------------------------------------------*/
- /*----------selection sort------------------*/
- //selectionsort(bsort,index);
- /*------------------------------------------*/
- /*----------Insertion sort------------------*/
- //insertionsort(bsort,index);
- /*------------------------------------------*/
- /*-----------Shell sort---------------------*/
- shellsort(bsort,index);
- /*------------------------------------------*/
- printf("/nFinal sorting result:/n");
- for(i=0;i<index;i++)
- {
- printf("%d ",bsort[i]);
- }
- return 0;
- }
冒泡排序、快速排序、选择排序、插入排序、shell排序C代码
最新推荐文章于 2024-08-04 15:02:35 发布