排序算法汇总之--选择排序(升序)

来源:互联网 发布:画框图的软件 编辑:程序博客网 时间:2024/05/18 03:52
/*排序算法汇总之——选择排序(升序)
仅以整型数组作算法demo,若想排序其它类型数据,在理解算法前提下,
稍作修改就能实现,比如:可以通过模板使函数通用化,使用函数对象
做参数来选择升序或降序
*/

//稳定性:不稳定排序
//最  优:
//最  坏:
//平  均:
//空  间:
/*
作者:刘东明
时间:2007年12月8日 10:24
博客:blog.sina.com.cn/dongmingliu
E-Mail:liu_dongming@qq.com
QQ:598741476
*/


#include
<iostream>
const int MAX = 10;
void selectSort(int a[], int n);
int main()
{
    
using std::cout;
    
using std::endl;
    
int i;
    
int intarr[MAX] = {2,4,8,1,5,0,9,3,6,7};
    cout
<<"选择排序前数组的顺序: ";
    
for(i = 0; i < MAX; i++)
    
{
        cout
<<intarr[i]<<"";
    }

    selectSort(intarr,MAX);
    cout
<<"选择排序前数组的顺序: ";
    
for(i = 0; i < MAX; i++)
    
{
        cout
<<intarr[i]<<"";
    }

    cout
<<endl;
    
return 0;
}


void selectSort(int a[], int n)
{
    
int i;
    
int j;
    
int smallIndex;        //最小值下标
    for(i = 0; i < n-1; i++)
    
{
        smallIndex 
= i;
        
for(j = i+1; j < n; j++)
        
{
            
if(a[smallIndex]>a[j])    //找出剩余子表中最小值的下标,赋给smallIndex
                smallIndex = j;    
        }

        
if(smallIndex != i)    //如果最小值的下标不是i,则交换
        {
            
int temp;
            temp 
= a[i];
            a[i] 
= a[smallIndex];
            a[smallIndex] 
= temp;
        }

    }

}