zoukankan      html  css  js  c++  java
  • 简单选择排序算法----(排序算法五)

    1.算法原理 

    找到数组中最小的元素与已好数组的最后一位元素交换位置

    49  38  65  97  76  13  27  49

    i=0   最小为13,交换49与13得[13] 38 65 97 76 [49] 27 49

    i=1   最小为27,交换38与27得13 [27] 65 97 76 49 [38] 49 

    i=2   最小为38,交换65与38得13 27 [38] 97 76 49 [65] 49 

    i=3   最小为49,交换97与49得13 27 38 [49] 76 [97] 65 49 

    i=4   最小为49,交换76与79得13 27 38 49 [49] 97 65 [76]

    i=5   最小为65,交换97与65得13 27 38 49 49 [65] [97] 76

    i=6   最小为76,交换97与76得13 27 38 49 49 65 [76] [97]

    排序结束

    2.代码实现

    #include <stdio.h>
    
    
    //printArray打印出数组
    void printArray(int a[],int size){  
        printf("数组为:[%d] ",a[0]);  
        for (int i=1;i<size;i++)  
        {  
            printf(" %d ",a[i]);  
        }  
        printf("
    ");  
    }
    
    //最出a[]中从start到end元素中的最小值的下标
    int  minIndex(int a[],int start,int end){
    	int minIndex=start;
    	for(int i=start+1;i<=end;i++){
    		a[i]<a[minIndex]?minIndex=i:0;
    	}
    	return minIndex;
    }
    
    void main()
    {
    	//a[0]为监视哨
    	int a[9]={0,49,38,65,97,76,13,27,49}; 
    	int n=8;
    	for (int i=1;i<=n-1;i++)
    	{
    		int index=minIndex(a,i,n);
    		printf("最小a[%d]=%d ",index,a[index]);
    		printArray(a,9);
    		a[0]=a[index];
    		a[index]=a[i];
    		a[i]=a[0];
    	}
    	printArray(a,9);
    	
    }
    

    3.排序结果

    最小a[6]=13 数组为:[0]  49  38  65  97  76  13  27  49
    最小a[7]=27 数组为:[13]  13  38  65  97  76  49  27  49
    最小a[7]=38 数组为:[27]  13  27  65  97  76  49  38  49
    最小a[6]=49 数组为:[38]  13  27  38  97  76  49  65  49
    最小a[8]=49 数组为:[49]  13  27  38  49  76  97  65  49
    最小a[7]=65 数组为:[49]  13  27  38  49  49  97  65  76
    最小a[8]=76 数组为:[65]  13  27  38  49  49  65  97  76
    数组为:[76]  13  27  38  49  49  65  76  97
    
    
    

  • 相关阅读:
    CF 149D Coloring Brackets(区间DP,好题,给配对的括号上色,求上色方案数,限制条件多,dp四维)
    hdu 4607 树形dp 树的直径
    poj 2955 区间dp入门题
    poj 2139 flord水题
    poj 2377 最大生成树
    lightoj 1422 区间dp
    模拟类似括号匹配
    nyoj 33 蛇形填数
    nyoj 2 括号配对问题水
    Hackonacci Matrix Rotations 观察题 ,更新了我的模板
  • 原文地址:https://www.cnblogs.com/whzhaochao/p/5023473.html
Copyright © 2011-2022 走看看