C++实现简单选择排序

来源:互联网 发布:淘宝售前售后客服 编辑:程序博客网 时间:2024/05/25 21:36

1>算法思想

2>算法实现

#include<iostream>using namespace std;#define ARRAY_SIZE 8/*description:在标准输出设备上显示数组元素。parameter:int* p:指向整形数组首元素的指针int length:整形数据长度*/void myshow(int*  p,int length){for(int i=0;i<length;i++){cout<<*(p+i)<<"\t";}cout<<endl;}//返回p_start[from ... to]中最小值的indexint selectMin(int *p_start,int from,int to){int index=from;//默认第一个数据为最小值for(int i=from+1;i<=to;i++){if(p_start[index]>p_start[i]){index=i;}}return index;}/*对p_start[0 ... length-1]进行选择排序*/void selectSort(int *p_start,int length){for(int i=0;i<length-1;i++){//length个数据进行选择排序只需进行length-1次选择即可//选择第i小的记录,并交换到位int min_index=selectMin(p_start,i,length-1);if(min_index!=i){//最小记录与第i个记录进行交换int temp=p_start[min_index];p_start[min_index]=p_start[i];p_start[i]=temp;}//展示中间结果cout<<"第"<<i<<"次选择排序中间结果"<<endl;myshow(p_start,length);}}int main(){int list[ARRAY_SIZE]={49,38,65,97,76,13,27,49};cout<<"排序前:"<<endl;myshow(list,ARRAY_SIZE);selectSort(list,ARRAY_SIZE);cout<<"排序后:"<<endl;myshow(list,ARRAY_SIZE);return 0;}

运行结果:


0 0
原创粉丝点击