zoukankan      html  css  js  c++  java
  • 几种排序算法小结

    插入排序, O(n^2), 从头到尾, 将较小的放在前面

    /* insertion sort ascending order */
     
    #include <stdio.h>
     
    int main()
    {
      int n, array[1000], c, d, t;
     
      printf("Enter number of elements
    ");
      scanf("%d", &n);
     
      printf("Enter %d integers
    ", n);
     
      for (c = 0; c < n; c++) {
        scanf("%d", &array[c]);
      }
     
      for (c = 1 ; c <= n - 1; c++) {
        d = c;
     
        while ( d > 0 && array[d] < array[d-1]) {
          t          = array[d];
          array[d]   = array[d-1];
          array[d-1] = t;
     
          d--;
        }
      }
     
      printf("Sorted list in ascending order:
    ");
     
      for (c = 0; c <= n - 1; c++) {
        printf("%d
    ", array[c]);
      }
     
      return 0;
    }
    

     冒泡排序, O(n^2), 将较大的放在后面。

    /* Bubble sort code */
     
    #include <stdio.h>
     
    int main()
    {
      int array[100], n, c, d, swap;
     
      printf("Enter number of elements
    ");
      scanf("%d", &n);
     
      printf("Enter %d integers
    ", n);
     
      for (c = 0; c < n; c++)
        scanf("%d", &array[c]);
     
      for (c = 0 ; c < ( n - 1 ); c++)
      {
        for (d = 0 ; d < n - c - 1; d++)
        {
          if (array[d] > array[d+1]) /* For decreasing order use < */
          {
            swap       = array[d];
            array[d]   = array[d+1];
            array[d+1] = swap;
          }
        }
      }
     
      printf("Sorted list in ascending order:
    ");
     
      for ( c = 0 ; c < n ; c++ )
         printf("%d
    ", array[c]);
     
      return 0;
    }
    
  • 相关阅读:
    leetcode-14
    贪心算法
    MySQL索引
    leetcode-13
    leetcode-12
    leetcode-11
    深度和广度优先搜索
    CentOS出错You don't have permission to access on this server
    linux给文件或目录添加apache权限
    让CentOS在同一个窗口打开文件夹
  • 原文地址:https://www.cnblogs.com/lumouren009/p/4315234.html
Copyright © 2011-2022 走看看