鸡尾酒排序

来源:互联网 发布:天睿软件科技有限公司 编辑:程序博客网 时间:2024/04/28 22:46

冒泡的变种

#include<stdio.h>    #include<stdbool.h>  void swap(int *a, int *b)   //交换两元素的值{    int t;    t = *a;    *a = *b;    *b = t;}void printArray(int a[], int count)   //打印数组元素{    int i;    for(i = 0; i < count; i++)        printf("%d ",a[i]);    printf("\n");}void bubble_sort(int a[], int size){        int i, bottom = 0,count = 1;    int top = size - 1;    int tag = 1;     while(tag)    //假如swapped = 0则没有元素交换,数组有序    {        tag = 0;         for(i = bottom; i < top; i++)//最大元素交换到最后         {            if(a[i] > a[i + 1])      //判断两个元素是否正确的顺序            {    printf("第%d次:   ",count++);                 printf(" %d<-->%d\n",a[i],a[i+1]);                swap(&a[i], &a[i + 1]);     //让两个元素交换顺序                printArray(a, size);                tag = 1;            }        }        top = top - 1;         for(i = top; i > bottom; i--)// 将最小元素交换到最前         {            if(a[i] < a[i - 1])             {printf("第%d次:   ",count++);                 printf(" %d<-->%d \n",a[i],a[i+1]);                swap(&a[i], &a[i - 1]);                printArray(a, size);                tag = 1;            }        }        bottom = bottom + 1;      }}int main(void)   {       int a[] = {0, 2, 1, 3, 4, 6, 9, 7, 8, 5};    int n = sizeof(a) / sizeof(*a);    printArray(a, n);    bubble_sort(a, n);}

结果:这里写图片描述

0 0
原创粉丝点击