• 交换排序算法实现


     

    #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;
        
    }

  • 相关阅读:
    Java学习之--List和ArrayList
    Linux
    Linux
    Docker 容器管理
    Docker 镜像管理
    如何理解 AWS VPC
    Linux 内核版本
    Windows 快速切换到当前目录下的dos环境
    Git 整理
    TCP/IP
  • 原文地址:https://www.cnblogs.com/seebro/p/2476550.html
Copyright © 2020-2023  润新知