zoukankan      html  css  js  c++  java
  • 数据结构排序-冒泡排序

    冒泡排序的主要过程:

    1. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。
    2. 对每一对相邻元素做同样的工作,从开始第一对到结尾的最后一对。比较一趟之后,最后的元素应该会是最大的数。
    3. 针对所有的元素重复以上的步骤,除了最后一个。
    4. 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 
     4 int n;
     5 
     6 /*
     7  * 冒泡排序
     8  */
     9 void BubbleSort(int *array)
    10 {
    11     int i, j, temp;
    12     for (i = 0; i < n - 1; i++)
    13     {
    14         for (j = 0; j < n - 1 - i; j++)
    15         {
    16             if (array[j] > array[j + 1])
    17             {
    18                 temp = array[j];
    19                 array[j] = array[j + 1];
    20                 array[j + 1] = temp;
    21             }
    22         }
    23     }
    24 }
    25 
    26 int main()
    27 {
    28     int i;
    29     int *array;
    30     printf("请输入数组的大小:");
    31     scanf("%d", &n);
    32     array = (int*) malloc(sizeof(int) * n);
    33     printf("请输入数据(用空格分隔):");
    34     for (i = 0; i < n; i++)
    35     {
    36         scanf("%d", &array[i]);
    37     }
    38     BubbleSort(array);
    39     printf("排序后为:");
    40     for (i = 0; i < n; i++)
    41     {
    42         printf("%d ", array[i]);
    43     }
    44     printf("
    ");
    45 }
  • 相关阅读:
    时尚前沿的图片左右滚动效果-1
    瀑布流效果
    js遮罩层弹出显示效果组件化
    javascript学习笔记(三)
    前端开发技巧
    Pushlet后台推送
    比较抽象的面试题
    技术点
    HTML5特性
    struts2学习笔记(二)
  • 原文地址:https://www.cnblogs.com/niceforbear/p/4533747.html
Copyright © 2011-2022 走看看