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

    好久没复习以前写的数据结构了,今天看了一段以前写的插入排序。

    插入排序原理:通俗讲,和打扑克牌整理牌是一个道理,从一堆混乱牌中,一张一张拿,拿一张后与前面排好的牌一个个比较,插入合适的位置。

    时间复杂度:O(n^2)

    /*插入排序2.0
    **此版本将创建数组函数删除,
    **创建数组与插入排序编排到
    **同一个函数里。
    */
    
    
    #include "stdafx.h"
    #include <stdio.h>
    
    #define M 1000
    
    void Insert_sorting(int a[],int n);//插入排序
    void Out_put(int a[], int n);//输出数组
    
    int main()
    {
        int n;
        int a[M] = {0};
    
        printf_s("输入待排序个数
    ");
        printf_s("n=");
        scanf_s("%d", &n);
    
        Insert_sorting(a,n);
        Out_put(a, n);
    
        return 0;
    }
    
    
    void Insert_sorting(int a[], int n)
    {
        int i, j, wep;//wep is 中间变量
    
        printf_s("请输入第1个值=");
        scanf_s("%d", &a[0]);
    
        for (i = 1; i < n; i++)
        {
            printf_s("请输入第%d个值=", i+1);
            scanf_s("%d", &a[i]);
    
            for (j = i;; j--)
            {
                if (j == 0)
                {
                    break;
                }
    
                if (a[j] < a[j - 1])
                {
                    wep = a[j - 1];
                    a[j - 1] = a[j];
                    a[j] = wep;
                }
                else
                {
                    break;
                }
            }
        }
    }
    void Out_put(int a[], int n)
    {
        int i;
    
        for (i = 0; i < n; i++)
        {
            printf_s("%d   ", a[i]);
        }
    }
  • 相关阅读:
    [Algorithms] Counting Sort
    [LeetCode] Sort Colors
    [LeetCode] Contains Duplicate III
    [LeetCode] Contains Duplicate
    [LeetCode] Two Sum II
    [LeetCode] Linked List Cycle II
    [LeetCode] Linked List Cycle
    [LeetCode] Longest Palindromic Substring
    [LeetCode] Two Sum
    [LeetCode] Rectangle Area
  • 原文地址:https://www.cnblogs.com/zpc-uestc/p/6280261.html
Copyright © 2011-2022 走看看