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

    插入排序(Insertion Sort)是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,通常采用in-place排序(即只需用到O(1)的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。

    算法描述:

      一般来说,插入排序都采用in-place在数组上实现。具体算法描述如下:

    1. 从第一个元素开始,该元素可以认为已经被排序
    2. 取出下一个元素,在已经排序的元素序列中从后向前扫描
    3. 如果该元素(已排序)大于新元素,将该元素移到下一位置
    4. 重复步骤3,直到找到已排序的元素小于或者等于新元素的位置
    5. 将新元素插入到该位置后
    6. 重复步骤2~5

    演示图:

         

    伪代码:

    1 INSERTION-SORT(A)
    2 for j = 2 to A.length
    3     key = A[j]
    4     i = j - 1
    5     while i > 0 and A[i] > key
    6         A[i+1] = A[i]
    7         i = i - 1
    8     A[i+1] = key

    代码详解:

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstdlib>
     4 #include <ctime>
     5 
     6 #define N 10
     7 
     8 using namespace std;
     9 
    10 void showData(int[], int);
    11 void insertionSort(int[], int);
    12 
    13 int main()
    14 {
    15     int i;
    16     int data[N];
    17     srand(time(NULL));
    18 
    19     for(i=0; i<N; i++) {
    20         data[i] = rand()%N;
    21     }
    22 
    23     showData(data, N);
    24 
    25     insertionSort(data, N);
    26 
    27     showData(data, N);
    28 
    29     return 0;
    30 }
    31 
    32 void showData(int arr[], int length) {
    33     int i;
    34     for(i=0; i<length; i++) {
    35         printf("%d ", arr[i]);
    36     }
    37     printf("
    ");
    38 }
    39 
    40 void insertionSort(int arr[], int length) {
    41     int i, j, key;
    42     for(j=1; j<length; j++){
    43         key = arr[j];
    44         i = j-1;
    45         while(i>=0 && arr[i]>key) {
    46             arr[i+1] = arr[i];
    47             i = i-1;
    48         }
    49         arr[i+1] = key;
    50     }
    51 }

    参考资料:维基百科

    转载请注明出处:http://www.cnblogs.com/michaelwong/p/4292162.html

  • 相关阅读:
    LeetCode 345. Reverse Vowels of a String 题解
    LeetCode 344. Reverse String 题解
    LeetCode 27. Remove Element 题解
    LeetCode 61. Rotate List 题解
    LeetCode 19.Remove Nth Node From End of List 题解
    Android耗电量
    Android 使用adb查看和修改电池信息
    Android AOP AspectJ 插桩
    Flask相关用法
    Monkey日志信息的11种Event percentage
  • 原文地址:https://www.cnblogs.com/michaelwong/p/4292162.html
Copyright © 2011-2022 走看看