编程实现直接插入排序、希尔排序、冒泡排序、快速排序、选择排序

来源:互联网 发布:白苹果的数据能恢复吗 编辑:程序博客网 时间:2024/06/05 16:06

代码

#include <iostream>using namespace std;//直接插入排序void insert_sort(int a[],int n){    int i , j , temp;    for(i = 1;i<n;i++)    {        temp = a[i];        for(j=i-1;j>=0&&temp<a[j]; j--)        {            a[j+1] = a[i];        }        a[j+1] = temp;      }}
//希尔排序//希尔排序实质上是一种分组插入排序void shell_sort(int a[],int n){    int h,i,j,temp;    for(h = n/2;h>0;h=h/2)    {        for(i = h;i<n;i++)        {            temp = a[i];            for(j = i-h;(j>=0&&temp<a[j]);j-=h)            {                a[j+h] =a[j];            }            a[j+h] = temp;        }    }}
//冒泡排序(原始)void bubble_sort(int a[],int len){    int i ,j,temp;    for(i = 0;i<len-1;i++)    {        for(j = len -1;j>=i;j--)        {            if(a[j+1]<a[j])            {                temp = a[j];                a[j] = a[j+1];                a[j+1] = temp;            }        }    }}
//改进版的冒泡排序void bubble_sort2(int a[],int len){    int i ,j,temp;    int exchange = 0;    for(i = 0;i<len-1;i++)    {        exchange = 0;        for(j = len-1;j>=i;j--)        {            if(a[j+1]<a[j])            {                temp = a[j];                a[j] = a[j+1];                a[j+1] = temp;                exchange = 1;            }        }        if(exchange!=1)            return;    }}
//快速排序void quick_sort(int a[],int len){    int i ,j,pivot;    if(low<high)    {        pivot = a[low];        i = low;        j = high;        while(i<j)        {            while(i<j&&a[j]>=pivot)                j--;            if(i<j)                a[i++] = a[j];            while(i<j&&a[i]<=pivot)                i++;            if(i<j)                a[j--] = a[i];        }        a[i] = pivot; //pivot移动到最终位置        quick_sort(a,low,i-1);        quick_sort(a,i+1,high);    }}
//选择排序(不稳定)void select_sort(int a[],int len){    int i,j,x,l;    for(i = 0;i<len;i++)    {        x=a[i];        l = i;        for(j = j ;j<len;j++)        {            if(a[j]<x)            {                x = a[j];                l = j;            }        }        a[l] = a[i];        a[i] = x;    }}
阅读全文
0 0
原创粉丝点击