zoukankan      html  css  js  c++  java
  • 交换排序算法实现

     

    #include <iostream>

    template <class elem>
    void swap(elem a[], int p1, int p2)
    {
         elem tmp = a[p1];
         a[p1] = a[p2];
         a[p2] = tmp;
    }

    template <class elem>
    void print(elem a[], int length)
    {
         for (int i = 0; i < length; i++)
             std::cout << a[i] << ' ';
         std::cout << std::endl;
    }

    template <class elem>
    void bub_sort(elem a[], int length)
    {
         for (int i = 0; i < length - 1; i++)
             for (int j = length - 1; j > i; j--)
                 if (a[j] < a[j-1])
                    swap(a, j, j-1);
    }

    template <class elem>
    void insert_sort(elem a[], int length)
    {
         for (int i = 1; i < length; i++)
             for (int j = i; j > 0; j--)
                 if (a[j] < a[j-1])
                    swap(a, j, j - 1);
    }

    template <class elem>
    void select_sort(elem a[], int length)
    {
         for (int i = 0; i < length - 1; i++)
         {
             int low_index = i;
             for (int j = length - 1; j > i; j--)
                 if (a[j] < a[low_index])
                    low_index = j;
             swap(a, low_index, i);
         }
    }
    int main(void)
    {
         int a[] = {42, 20, 17, 13, 28, 14, 23, 15};
         print(a, 8);
         select_sort(a, 8);
         print(a, 8);
         system("pause");
         return 0;
        
    }

  • 相关阅读:
    数据结构--线性表和链表的基础知识
    OC基础--字符串
    iOS开发知识梳理博文集
    OC基础--数据类型与表达式
    数据结构概述
    数据结构--栈和队列基础知识
    NodeJS Get/Post 参数获取
    NodeJS + express 添加HTTPS支持
    NodeJS 获取系统时间 并格式化输出
    Node.Js + Express 搭建服务器
  • 原文地址:https://www.cnblogs.com/seebro/p/2476550.html
Copyright © 2011-2022 走看看