zoukankan      html  css  js  c++  java
  • 插入排序

     1 #include <iostream>
     2 #include <cstdlib>
     3 
     4 #define ARR_SIZE 10
     5 
     6 using namespace std;
     7 
     8 /* 想象一下打牌时发完牌整理的时候,不同的是打牌我们一眼就能看出来这张牌应该插在哪个位置,而插入排序要逐一去对比前面已排好的元素,逐一去交换 */
     9 void insertsort(int a[]);
    10 void CreateRandArr(int a[]);
    11 
    12 int main()
    13 {
    14     int a[ARR_SIZE];
    15     int i;
    16     CreateRandArr(a);
    17     insertsort(a);
    18     cout << "after sort: " << endl;
    19     for(i=0;i<ARR_SIZE;i++)
    20     {
    21         cout << a[i] << ' ' ;
    22     }
    23     
    24     return 0;
    25 }
    26 
    27 void insertsort(int a[])
    28 {
    29     int i, j, temp;
    30     for(i=1; i<ARR_SIZE; i++)    /* i不能从0开始。否则j-1小于0 */
    31     {
    32         for(j = i; j>0 && a[j]<a[j-1]; j--)
    33         {
    34             temp = a[j];
    35             a[j] = a[j-1];
    36             a[j-1] = temp;
    37         }
    38     }
    39 }
    40 
    41 void CreateRandArr(int a[])
    42 {
    43     int i;
    44     for(i=0;i<ARR_SIZE;i++)
    45     {
    46         a[i] = rand() % 100;
    47         cout <<a[i] << ' ' ; 
    48     }
    49     cout << endl;
    50 }
  • 相关阅读:
    SQL Server 2005 出现“此数据库没有有效所有者”错误的解决方法
    使用swfupload出现SecurityError Error #2156问题
    读取Excel表
    POJ 1953 (DP)
    POJ 1050 (DP)
    POJ 1276 (DP)
    POJ 1579 (DP)
    HDOJ 4223 (DP)
    POJ 1080 (DP)
    POJ 1458 (DP)
  • 原文地址:https://www.cnblogs.com/tan-wm/p/14397477.html
Copyright © 2011-2022 走看看