排序算法

#include <stdio.h>

/*
*插入排序,
*/
void insertSort(int a[],int n){
    
    for(int i=1;i<n;i++){
        //find insert location
        int j=0;
        while(a[j]<a[i] && j<i){
            j++;
        }

//向右移动数据,插入数据
        if(i !=j){
            int temp=a[i];
        //>a[i]的向后移
            for(int k=i;k>j;k--){
                a[k]=a[k-1];
            }
            a[j]=temp;
        }
    }
}

/*
* 选择排序,依次选出本轮最小的排在前面,1 round 第一小,2 round 第二小。。。
*/
void selectSort(int a[],int n){
    // compare n-1 rounds
    for(int i=0;i<n-1;i++){
        int min_index=i;
        //i+1.....n-1 compare
        for(int j=i+1;j<n;j++){
            if(a[j]<a[min_index]){
                min_index=j;
            }
        }
        //exchange numbers
        if(i != min_index){
            int temp=a[min_index];
            a[min_index]=a[i];
            a[i]=temp;
        }
    }
}

/*
*冒泡排序,每次找出本轮最大的排在数组后面,1 round最大的排在最后,2 round找出第二大的排在倒数第二个。。。
*/
void maoPao(int a[],int n){
    //compare n-1 rounds
    for(int i=0;i<n-1;i++){
        for(int j=0;j<n-1-i;j++){
            if(a[j]>a[j+1]){
                int temp=a[j+1];
                a[j+1]=a[j];
                a[j]=temp;
            }
        }
    }
}

int main() {
    int a[]={3,2,4,1,7,6,5,8};
    //selectSort(a,8);
    //maoPao(a,8);
    insertSort(a,8);
    for(int i=0;i<8;i++){
        printf("%d",a[i]);
        printf("\t");
    }

    return 0;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容