C语言四种常用排序

来源:互联网 发布:盛世网络剧在线观看 编辑:程序博客网 时间:2024/05/21 09:45

//冒泡排序 稳定

void sort1(int a[],unsignedint n){

    for (int i = 0; i < n ;i++) {

        for (int j = i +1; j < n  ;j++) {

            if(a[i]>a[j]){

                a[i] = a[j] + a[i];

                a[j] = a[i] - a[j];

                a[i] = a[i] - a[j];

            }

        }

    }

}


//选择排序 不稳定

void sort2(int a[],unsignedint n){

    int temp = 0;

    int index = 0;

    for (int i = 0; i < n ;i++) {

        temp = a[i];

        index = i;

        for (int j = i +1; j < n;j++) {

            if( a[j] < temp){

                temp = a[j];

                index = j;

            }

        }

        if(i==index){

            continue;

        }else{

            a[i] = a[index] + a[i];

            a[index] = a[i] - a[index];

            a[i] = a[i] - a[index];

        }

    }

}


//插入排序 稳定


void sort3(int a[],unsignedint n){

    int temp=0;

    for (int i = 0; i < n ;i++) {

        for (int j =0; j < i  ;j++) {

            if(a[i] < a[j]){

                temp = a[i];

                for(int k = i; k > j;k--){

                    a[k] = a[k-1];

                }

                a[j] = temp;

            }

        }

    }

}



void sortRecursive(int a[],int first,int last){

    int temp=0;

    int index=first;

    for(int i=first;i<=last;i++){

        if(a[i]<a[index]){

            temp = a[i];

            for(int k = i; k > index;k--){

                a[k] = a[k-1];

            }

            a[index] = temp;

            index++;

        }

    }

    if(last==first||last-first==1||first>last){

        return;

    }

    sortRecursive(a, first, index - 1);

    sortRecursive(a, index + 1, last);

}


//快速排序 不稳定

void sort4(int a[],unsignedint n){

    int i=0;

    int j=n-1;

    sortRecursive(a, i, j);

}

原创粉丝点击