排序(三)

xiaoxiao2021-02-28  66

二、交换类排序

        思想:

                通过一系列交换逆序元素进行排序的方法。

    (1)冒泡排序

            ***思想

                    每次扫描顺次比较相邻的两个元素的大小,若逆序就交换位置,反复扫描,直到待排序记录序列没有逆序为止。

            ***算法

                    void BubbleSort(RecordType r[],int n)

                    {

                            int i,j;

                            RecordType x;

                            for(i = 1 ; i<=n-1 ; i++)

                            {

                                    for(j = 1 ; j<=n-i ; j++)

                                    {

                                            if(r[j].key>r[j+1].key)

                                            {

                                                    x = r[j];

                                                    r[j] = r[j+1];

                                                    r[j+1] = x;

                                            }

                                    }

                            }

                    }

            ***案例

                    #include<stdio.h>                    #include<stdlib.h>                    typedef int KeyType;                    typedef int OtherType;                    typedef struct _RecordType                    {                 KeyType key;                 OtherType other_data;                    }RecordType;                    void BubbleSort(RecordType r[],int n)                    {                 int i,j;                 RecordType x;                 for(i = 1;i<=n-1;i++)                 {                  for(j = 1;j<=n-i;j++)             {             if(r[j].key>r[j+1].key)             {                  x = r[j];             r[j] = r[j+1];             r[j+1] = x;             }             }                 }                    }                    int main()                    {                 int i;                 int len;                 RecordType r[20];                 printf("请输入数组的长度:\n");                 scanf("%d",&len);                 for(i = 1;i<=len;i++)                 {             printf("请输入数组中第%d个元素   ",i);             scanf("%d",&r[i].key);                 }                 printf("\n");                 printf("排序前的结果:\n");                 for(i = 1;i<=len;i++)                 {             printf("%d  ",r[i].key);                 }                 printf("\n");                 BubbleSort(r,len);                 printf("排序后的结果:\n");                 for(i = 1;i<=len;i++)                 {             printf("%d  ",r[i].key);                 }                 printf("\n");                 return 0;                    }

转载请注明原文地址: https://www.6miu.com/read-2350340.html

最新回复(0)