zoukankan      html  css  js  c++  java
  • C++数据结构与算法:选择排序

    选择排序也是一种简单排序。这种排序的算法是:首先找出最大的元素,把它移动交换到a[n-1],然后在余下的n-1个元素中选择最大的元素并把它移动交换到a[n-2],如此迭代下去即可完成排序。代码如下:

    复制代码
    // BubbleSort.cpp : 定义控制台应用程序的入口点。
    //
    

     

    // SelectionSort.cpp : 定义控制台应用程序的入口点。
    //
    #include "stdafx.h"
    #include <cmath>
    #include <iostream>
    using namespace std;
    #define  MAXNUM 20
    
    template<typename T>
    void Swap(T& a, T& b)
    {
        int t = a;
        a = b;
        b = t;
    }
    template<typename T>
    int Max(T a[], int n)
    {//寻找数组a[0:n-1]中最大元素的位置
        int pos = 0;
        for(int i =1 ;i < n; i++)
        {
            if(a[pos] < a[i])
                pos = i;
        }
        return pos;
    }
    template<typename T>
    void SelectSort(T a[],int n)
    {//对数组a[0:n-1]中的n个元素进行选择排序
        for(int size = n;size > 1; size--)
        {
            int j = Max(a,size);
            Swap(a[j],a[size-1]);
        }
            
    }
    int _tmain(int argc, _TCHAR* argv[])
    {
        int a[MAXNUM];
        for(int i = 0 ;i< MAXNUM; i++)
        {
            a[i] = rand()%(MAXNUM*5);
        }
        
        for(int i =0; i< MAXNUM; i++)
            cout << a[i] << "  ";
        cout << endl;
        SelectSort(a,MAXNUM);
        cout << "After BubbleSort: " << endl;
        for(int i =0; i< MAXNUM; i++)
            cout << a[i] << "  ";
        cin.get();
    
        return 0;
    }
  • 相关阅读:
    Ruby
    WebGL的第二个小程序
    wegGL的第一个小程序
    Node.js介绍
    接口隔离原则(Interface Sepreation Principle)
    参数
    字段/属性
    接口和抽象类
    javascript中的事件
    线性回归算法-4.多元线性回归算法
  • 原文地址:https://www.cnblogs.com/JczmDeveloper/p/3038908.html
Copyright © 2011-2022 走看看