排序的几种常用方法

这是电子科技大学软件技术基础课程的练习题,源码在 Github 上有,需要的话取用,最好能注明出处,谢谢。


选择排序

//  Created by Toxni on 12/28/15.
//  Copyright © 2015 Toxni. All rights reserved.

#include <stdio.h>

void selectSort(int arr[], int len) {

    int i,j,temp;
    for(i = 0; i < len; i++)
    {
        for(j = i + 1; j < len; j++)
        {
            if(arr[i]>arr[j])
            {
                temp=arr[i];
                arr[i]=arr[j];
                arr[j]=temp;
            }
        }
    }
}

int main() {  
    int i;
    int a[10]={513, 87, 512, 61, 908, 170, 897, 275, 653, 462};
    printf("arr before sort is: \n");
    for (i = 0;i < 10;i++) {

        printf("%d ",a[i]);
    }

    selectSort(a, 10);

    printf("\narr after sort is: \n");
    for (i = 0;i < 10;i++) {

        printf("%d ",a[i]);
    }
    printf("\n");
}


插入排序

//  Created by Toxni on 12/28/15.
//  Copyright © 2015 Toxni. All rights reserved.

#include <stdio.h>

void insertSort(int arr[],int len)  
{
    int i,j;
    int key;
    for(i=1;i<len;i++)
    {
        key=arr[i];
        for(j=i-1;j>=0;j--)
        {
            if(arr[j]>key)
                arr[j+1]=arr[j];
            else
                break;
        }
        arr[j+1]=key;
    }
}


int main() {  
    int i;
    int a[10]={513, 87, 512, 61, 908, 170, 897, 275, 653, 462};
    printf("arr before sort is: \n");
    for (i = 0;i < 10;i++) {

        printf("%d ",a[i]);
    }

    insertSort(a, 10);

    printf("\narr after sort is: \n");
    for (i = 0;i < 10;i++) {

        printf("%d ",a[i]);
    }
    printf("\n");
}


冒泡排序

//  Created by Toxni on 12/28/15.
//  Copyright © 2015 Toxni. All rights reserved.

#include <stdio.h>

void bubbleSort(int arr[],int len)  
{
    int i,j,temp;
    for(i=0;i<len;i++)
    {
        for(j=0;j<len-i-1;j++)
        {
            if(arr[j]>arr[j+1])
            {
                temp=arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;
            }
        }
    }
}


int main() {  
    int i;
    int a[10]={513, 87, 512, 61, 908, 170, 897, 275, 653, 462};
    printf("arr before sort is: \n");
    for (i = 0;i < 10;i++) {

        printf("%d ",a[i]);
    }

    bubbleSort(a, 10);

    printf("\narr after sort is: \n");
    for (i = 0;i < 10;i++) {

        printf("%d ",a[i]);
    }
    printf("\n");
}